package com.epalmpay.service.weixin.impl;

import com.epalmpay.dto.memberGrade.MemberGradeOutDTO;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.bonus.IBonusService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.activity.CouponHelp;
import com.epalmpay.dto.member.SubscribeMemberDTO;
import com.epalmpay.dto.memberGrade.FeeOutDTO;
import com.epalmpay.dto.messsage.SysMessageOutDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.*;
import com.epalmpay.payplat.result.*;
import com.epalmpay.service.activity.IActivityRedPackageService;
import com.epalmpay.service.activity.IActivityUnroutineService;
import com.epalmpay.service.activity.ICouponUserService;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxApiMemberService;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import com.epalmpay.util.code.CodeUtil;
import com.epalmpay.util.code.QRCodeParams;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


@Service("wxApiMemberService")
public class WxApiMemberServiceImpl implements IWxApiMemberService {

	@Resource
	private MemberCardMapper memberCardMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private MallGoodCommentMapper mallGoodCommentMapper;
	@Resource
	private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
	@Resource
	private OrderServiceGoodMapper orderServiceGoodMapper;
	@Resource
	private IActivityUnroutineService activityUnroutineService;
	@Resource
	private ActivityRoutineRegisterMapper activityRoutineRegisterMapper;
	@Resource
	private IRedPackageUserService redPackageUserService;
	@Resource
	private ICouponUserService couponUserService;
    @Resource
	private IActivityRedPackageService activityRedPackageService;
    @Resource
	private MallCartMapper mallCartMapper;
    @Resource
	private MemberAddressMapper memberAddressMapper;
	@Resource
	private MainAdvertMapper mainAdvertMapper;
    @Resource
    private SysMessageInfoMapper sysMessageInfoMapper;
    @Resource 
	private GroupPayconfigMapper groupPayconfigMapper;
    @Resource
	private MemberGradeMapper memberGradeMapper;
    @Resource
	private OrderShopMapper orderShopMapper;
    @Resource
	private ShopMapper shopMapper;
    @Resource
   	private MemberFeeMapper memberFeeMapper;
    @Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private CouponMapper couponMapper;
	@Resource
	private ActivityUnroutineMapper activityUnroutineMapper;
	@Resource
	private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;
	@Resource
	private GroupConfigMapper groupConfigMapper;
	@Resource
	private MallEntityGoodSpecMapper mallEntityGoodSpecMapper;
	@Resource
	private IBonusService bonusService;
	@Autowired
	@Lazy
	private ITemplateMailSendService templateMailSendService;
	
	@Resource
	private IWalletService walletService;

	protected com.epalmpay.util.Logger logger = com.epalmpay.util.Logger.getLogger(this.getClass());

	public Response bankList(String memberId) throws ApplicationException{
		Map<String, Object> map = new HashMap<String, Object>();
		List<MemberCard> memberCards = memberCardMapper.selectByMemberId(Long.parseLong(memberId));
		if(memberCards.size()==0){
			return Response.getError("银行卡信息不存在");
		}
		List<Map<String,Object>> bankList = new ArrayList<Map<String, Object>>();
		for(MemberCard memberCard:memberCards){
			Map<String, Object> detail = new HashMap<String, Object>();
			detail.put("id",memberCard.getId().toString());
			detail.put("card_num", StringReplaceUtil.bankCardReplaceWithStar(memberCard.getCardNum().toString()));
			detail.put("bank_name",memberCard.getIssuerBankName());
			detail.put("card_status", BizEnum.CardStatus.fromType(memberCard.getCardStatus()).getName());
			detail.put("card_type", BizEnum.BindCardType.fromType(memberCard.getBindCardType()).getName());
			bankList.add(detail);
		}
		if(bankList.size()>0) {
			map.put("bank_list", bankList);
		}
		return Response.getSuccess(map);
		
	}
	
	@Override
	public Response bankListSort(String memberId) throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		List<MemberCard> memberCards = memberCardMapper.selectByMemberId(Long.parseLong(memberId));
		if(memberCards.size()==0){
			//throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
			return Response.getSuccessExtend(null,null);
		}
		List<Map<String,Object>> bankList1 = new ArrayList<Map<String, Object>>();
		List<Map<String,Object>> bankList2 = new ArrayList<Map<String, Object>>();
		for(MemberCard memberCard:memberCards){
			if(memberCard.getBindCardType().equals(BizEnum.BindCardType.QuickPayCard.getType())){
				Map<String, Object> detail = new HashMap<String, Object>();
				detail.put("cardId",memberCard.getId().toString());
				detail.put("cardNum", StringReplaceUtil.bankCardReplaceWithStar(memberCard.getCardNum().toString()));
				detail.put("cardAccountType", BizEnum.CardType.fromType(memberCard.getCardType()).getName());
				detail.put("cardAccountTypeValue", memberCard.getCardType());
				detail.put("cardIssuerId", memberCard.getIssuerBankName());
				detail.put("cardAccName", memberCard.getIdName());
				detail.put("cardNo", memberCard.getIdNo());
				detail.put("cardIntegral", memberCard.getBankIntegral());
				detail.put("cardMobile", memberCard.getCardMobile());
				detail.put("cvn", memberCard.getCardCvn());
				detail.put("expdate", memberCard.getCardExpdate());
				detail.put("cardType", memberCard.getBindCardType());
				detail.put("cardStatus", "1");
				bankList1.add(detail);
			}else if(memberCard.getBindCardType().equals(BizEnum.BindCardType.WithDrawCard.getType())){
				Map<String, Object> detai2 = new HashMap<String, Object>();
				detai2.put("cardId",memberCard.getId().toString());
				detai2.put("cardNum", StringReplaceUtil.bankCardReplaceWithStar(memberCard.getCardNum().toString()));
				detai2.put("cardAccountType", BizEnum.CardType.fromType(memberCard.getCardType()).getName());
				detai2.put("cardAccountTypeValue", memberCard.getCardType());
				detai2.put("cardIssuerId", memberCard.getIssuerBankName());
				detai2.put("cardAccName", memberCard.getIdName());
				detai2.put("cardNo", memberCard.getIdNo());
				detai2.put("cardIntegral", memberCard.getBankIntegral());
				detai2.put("cardMobile", memberCard.getCardMobile());
				detai2.put("cvn", memberCard.getCardCvn());
				detai2.put("expdate", memberCard.getCardExpdate());
				detai2.put("cardType", memberCard.getBindCardType());
				detai2.put("cardStatus", "1");
				bankList2.add(detai2);
			}
		}
		return Response.getSuccessExtend(bankList2,bankList1);
	}

	public Map<String, Object> bankCardDetil( String memberId,String cardId) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
//		MemberCard memberCard = memberCardMapper.selectByPrimaryKey(Long.parseLong(cardId));
		MemberCard memberCard = memberCardMapper.selectMemberCardInfo(Long.parseLong(cardId));
		if(memberCard != null){
			map.put("card_num",memberCard.getCardNum());
			map.put("bank_name",memberCard.getIssuerBankName());
			map.put("card_desc",memberCard.getBankDesc());
			map.put("bank_zone",memberCard.getBankZone());
			map.put("bind_card_type", BizEnum.BindCardType.fromType(memberCard.getBindCardType()).getName());
			map.put("card_status",BizEnum.CardStatus.fromType(memberCard.getCardStatus()).getName());
			map.put("id_no",memberCard.getIdNo());
			map.put("id_name",memberCard.getIdName());
			map.put("phone",memberCard.getPhone());
		}
		return map;
	} 

	public Boolean updateUnBindBankCard(String memberId, String cardId) throws Exception{
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		memberCard.setGmtModified(new Date());
		memberCard.setCardStatus(BizEnum.CardStatus.DeleteBind.getType());
		memberCardMapper.updateByPrimaryKey(memberCard);
		return true;
	}
	@Override
	public Map<String, Object> updateMemberBankCard(String memberId, String accName, String accNo, String bankName,
			String certNo, String mobile, String payPwd,String cardType,String bankCode) throws ApplicationException {
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		//用户名
		String customerName=null;
		if(member.getApproveStatus()==null||member.getApproveStatus()==0){
			customerName=accName;
		}else{
			customerName=member.getName();
		}	
	
		
		if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
			throw new ApplicationException(Rescode.FAIL, "支付密码错误");
		}
		MemberCard memberCardName=memberCardMapper.selectByPrimaryName(Long.parseLong(memberId));
		if(memberCardName!=null&&!memberCardName.getIdName().equals(accName)){
			throw new ApplicationException(Rescode.FAIL, "此卡认证信息与初次认证信息不一致");
		}
		/**
		 * 账户类型信息查询
		 */
		String cardTypeValue=null;
		String bank=null;
		Map<String, String> mapCardNum=IPayAPI.queryCardCodeNew(accNo);
		
		if(mapCardNum.get("Rcd").equals("0000")){
			cardTypeValue=mapCardNum.get("Ctp");
			bank=mapCardNum.get("Cnm");
		}else if("5505".equals(mapCardNum.get("Rcd"))){
			QueryCardCode queryCardCode=QueryCardCode.initialize(member.getPayGroupCode(), accNo);
			PayCardCodeResult cardAccountTypeResult=IPayAPI.queryCardCode(queryCardCode);
			if(cardAccountTypeResult==null || !PayCardCodeResult.SUCCESS.equals(cardAccountTypeResult.getRespCode())){
				throw new ApplicationException(Rescode.FAIL, "获取银行卡账户类型失败");
			}else{
				cardTypeValue=cardAccountTypeResult.getResult().get("CardType");
			}
		}else{
			throw new ApplicationException(Rescode.FAIL, mapCardNum.get("RDesc"));
		}
		 //只需比较前4位code是否一致即可
		 String bankCodeNew=mapCardNum.get("InsCd");
		//检验银行
		String bankCode_=null;
		if(memberCardName!=null&&!bankName.contains(memberCardName.getIssuerBankName())){
			if(StringUtils.isNotBlank(bankCodeNew)&&StringUtils.isNotBlank(bankCode)){
				 bankCodeNew=bankCodeNew.substring(2,6);
				 if(bankCode.length()==8){
					 bankCode_=bankCode.substring(0,4);
				 }else{
					 bankCode_=bankCode.substring(2,6);
				 }
				 if(!bankCodeNew.equals(bankCode_)){
					 throw new ApplicationException(Rescode.FAIL,"检测卡号的银行为："+bank+",你选择的银行为:"+bankName);
				 }
			}else{
				throw new ApplicationException(Rescode.FAIL,"检测卡号的银行为："+bank+",你选择的银行为:"+bankName);
			}
			
		}		
		if(cardType!=null){
			//检测卡类型
			if(!cardType.equalsIgnoreCase(cardTypeValue)&&!cardType.equalsIgnoreCase("03")){
				String cardAccountType1= Tools.convertTypeValue(cardType);
				String cardAccountType2= Tools.convertTypeValue(cardTypeValue);
				String msg=String.format("你需要绑定的是%s，此卡为%s,不符合要求",cardAccountType1,cardAccountType2);
				throw new ApplicationException(Rescode.FAIL,msg);
			}
		}
		     //绑定了快捷支付卡,则不能重新绑定提现银行卡 已快捷卡失败了  可继续绑提现卡
				MemberCard memberCard =  memberCardMapper.selectCardNum(Long.parseLong(memberId),accNo,bankCode);
				if(memberCard==null){
					MemberCard record = new MemberCard();
					record.setGmtCreate(new Date());
					record.setGmtModified(new Date());
					record.setMemberId(Long.parseLong(memberId));
					record.setBankIntegral(bankCode);
					record.setCardNum(accNo);//卡号
					record.setIdName(customerName);
					record.setIdNo(certNo);//身份证号
					record.setCardMobile(mobile);
					if(cardType.equalsIgnoreCase("01")){
						record.setCardType(BizEnum.CardType.DebitCard.getType()); 
					}else if(cardType.equalsIgnoreCase("02")){
						record.setCardType(BizEnum.CardType.CreditCard.getType()); 
					}
					record.setCardCvn(null);
					record.setCardExpdate(null);
					record.setBindCardType(BizEnum.BindCardType.WithDrawCard.getType());
					record.setCardStatus(BizEnum.CardStatus.Verified.getType());
					record.setBankZone(null);//开户地区
					bankDesc(record, bankCode); 
				    memberCardMapper.insert(record);
				    param.put("cardId", record.getId());
				}else if(memberCard!=null&&memberCard.getCardStatus()==BizEnum.CardStatus.Verified.getType()){
					throw new ApplicationException(Rescode.FAIL, "该卡已认证，无需重复认证");
				}else{
					memberCard.setGmtCreate(new Date());
					memberCard.setGmtModified(new Date());
					memberCard.setMemberId(Long.parseLong(memberId));
					memberCard.setBankIntegral(bankCode);
					memberCard.setCardNum(accNo);//卡号
					memberCard.setIdName(customerName);
					memberCard.setIdNo(certNo);//身份证号
					memberCard.setCardMobile(mobile);
					if(cardType.equalsIgnoreCase("01")){
						memberCard.setCardType(BizEnum.CardType.DebitCard.getType()); 
					}else if(cardType.equalsIgnoreCase("02")){
						memberCard.setCardType(BizEnum.CardType.CreditCard.getType()); 
					}
					memberCard.setCardCvn(null);
					memberCard.setCardExpdate(null);
					memberCard.setBindCardType(BizEnum.BindCardType.WithDrawCard.getType());
					memberCard.setCardStatus(BizEnum.CardStatus.Verified.getType());
					memberCard.setBankZone(null);//开户地区
					bankDesc(memberCard, bankCode);
					memberCardMapper.updateByPrimaryKey(memberCard);
				}
		String orgOrderNum = UtilFun.createOrderNum();
		Date date=new Date();
		
		//用户绑卡 01借记卡 00 信用卡
		String accountType="01";
		if(cardType.equalsIgnoreCase("02")){
			accountType="00";
		}
		PayBindBankCard bbc=PayBindBankCard.initialize(
				member.getVirtualCard(), 
				payPwd, 
				orgOrderNum,
				member.getPayGroupCode(),
				DateUtil.fomatDate(date,DateUtil.sdfTimes), 
				orgOrderNum,
				accNo,
				customerName, //CustomerName
				accountType,
				mobile,
				certNo,
				BizEnum.WithdrawBankList.fromType(bankCode).getName(),//银行名称 
				"000000000000",//联行号
				BizEnum.WithdrawBankList.fromType(bankCode).getName(),//开户行名称
				1, 
				"22");
		
			//如果未实名认证 先修改用户资料信息实名认证
			if(member.getApproveStatus()==null||member.getApproveStatus()==0){
			//修改会员为已认证
			    member.setApproveStatus(1);
			    member.setName(customerName); 
			    member.setIdNo(certNo); 
				memberMapper.updateByPrimaryKeySelective(member);
			    PayUpdateData ud=PayUpdateData.initialize(
					   member.getPayGroupCode(),
					   member.getVirtualCard(),
			    		customerName,
						member.getPhone(),
						certNo,
						DateUtil.fomatDate(new Date(),DateUtil.sdfTimes),
						member.getUserId()+"@163.com",
						null,
						null,"1");
			    PayResult payResultCert=IPayAPI.updateAccountData(ud);
			    if(!PayResult.SUCCESS.equals(payResultCert.getRespCode())){
			    	throw new ApplicationException(Rescode.FAIL,payResultCert.getMsgTxt());
			    }
		}
		logger.info("++++++++++bbc++++"+bbc);
		PayResult payResult=IPayAPI.userBindBankCard(bbc);
		if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		return param;
	}
	
	
	
	/**
	 * 
	 * @param member
	 * @param orderAmount 赠送金额
	 * @param relatedTradeOfflineId
	 * @param relatedActivityId
	 * @return
	 */
	   public TradeOffline recordRecharge(Member member,Integer orderAmount,Long relatedTradeOfflineId,Long relatedActivityId,String OrgOrderNum) {
	        TradeOffline recordRecharge = new TradeOffline();
	            recordRecharge.setRelatedTradeOfflineId(relatedTradeOfflineId);//关联交易记录ID
	            recordRecharge.setRelatedActivityId(relatedActivityId);//关联活动ID
	            recordRecharge.setMemo("银行卡线上充值返现");
		    	recordRecharge.setDetail("银行卡上充值返现");//详情
		    	recordRecharge.setTransactionType((byte)BizEnum.TransactionType.RechargeBackCash.getType());
		    	recordRecharge.setGmtCreate(new Date());
		    	recordRecharge.setGmtModified(new Date());
		    	recordRecharge.setGroupId(member.getGroupId());
		    	recordRecharge.setOrderId(OrgOrderNum); 
		    	recordRecharge.setPayerId(member.getId());//会员id
		    	recordRecharge.setPayerName(member.getName());
		    	recordRecharge.setPayerType((byte) CommonEnum.UserType.User.getType());
		    	recordRecharge.setReceiverId(member.getId()+"");//接收者id
		    	recordRecharge.setReceiverName(member.getName());//接收者
		    	recordRecharge.setReceiverType((byte) CommonEnum.UserType.User.getType());
		    	recordRecharge.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    	recordRecharge.setOrderAmount(orderAmount); 
		    	recordRecharge.setDiscountAmount(0);//折扣金额
		    	recordRecharge.setRealAmount(orderAmount);//实付金额
		    	recordRecharge.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
		    	recordRecharge.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());
		    	recordRecharge.setIsWallet(true);
		    	recordRecharge.setTermSerial(null);
		    	recordRecharge.setMerchantNo(null);//商户号
		    	recordRecharge.setTerminalNo(null);//商户终端号
		    	recordRecharge.setTransNo(null); //交易流水号
		    	recordRecharge.setTransOrderNo(null);//交易机构订单号
		    	recordRecharge.setPayAccount("");//支付卡号
		    	recordRecharge.setScanOrganization(null);//扫码付入网机构
		    	recordRecharge.setCrcodeStr(null); 
		    	recordRecharge.setOldOrderId(null); 
		    	recordRecharge.setDividableAmount(0);//可分润金额
		    	recordRecharge.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		     	recordRecharge.setPayOrderid(OrgOrderNum);
		    	recordRecharge.setPayBakOrderid(null);
		    	recordRecharge.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());//入网机构
			return recordRecharge;
		}
	
	
	public Map<String, Object> insertBankCardVefity(String memberId,String tranAmt, String bankCode,String cardNum,
									String idName,String idNo,String cardMobile,
									String cardCvn,String cardExpdate,String Ip,String payType) throws ApplicationException{
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		//校验卡是否支持绑定 提高绑卡成功率  
		Map<String, String> mapCardNum=IPayAPI.queryCardCodeNew(cardNum);
		if(!mapCardNum.get("Rcd").equals("0000")){
			throw new ApplicationException(Rescode.FAIL, "该卡暂不支持快捷绑定,请换张卡再试");
		}
		if(!mapCardNum.get("InsCd").startsWith(bankCode.substring(0,6))){ 
			throw new ApplicationException(Rescode.FAIL, "您输入的卡号是"+mapCardNum.get("Cnm"));
		}
		MemberCard memberCardName=memberCardMapper.selectByPrimaryName(Long.parseLong(memberId));
		if(memberCardName!=null&&!memberCardName.getIdName().equals(idName)){
			throw new ApplicationException(Rescode.FAIL, "此卡认证信息与初次认证信息不一致");
		}
		//验证该卡是否绑定过
		MemberCard memberCard =  memberCardMapper.selectOneSuccessByMemberId(Long.parseLong(memberId),cardNum,bankCode,BizEnum.BindCardType.QuickPayCard.getType());
		int cardType=BizEnum.CardType.DebitCard.getType();
		String cvnStr=null;
		//此处调用绑卡接口
		if(Tools.notEmpty(cardCvn)&&Tools.notEmpty(cardExpdate)){
			cardType=BizEnum.CardType.CreditCard.getType();
			cvnStr=cardCvn+";"+cardExpdate;
		}
		if(memberCard==null){
			MemberCard record = new MemberCard();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setMemberId(Long.parseLong(memberId));
			record.setBankIntegral(bankCode);
			record.setCardNum(cardNum);
			record.setIdName(idName);
			record.setIdNo(idNo);
			record.setCardMobile(cardMobile);
			record.setCardType(cardType); 
			record.setCardCvn(cardCvn);
			record.setCardExpdate(cardExpdate);
			record.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
			record.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
			record.setBankZone(null);//开户地区
			bankDesc(record, bankCode); 
		    memberCardMapper.insertSelective(record);
		    if(member.getIdNo().equals("000000000000000000")|| member.getApproveStatus() == BizEnum.ApproveStatus.UnVerify.getType()){
				    	member.setIdNo(idNo);
				    	member.setName(idName);
				    	member.setApproveStatus(BizEnum.ApproveStatus.Verified.getType());
				    	memberMapper.updateByPrimaryKeySelective(member);
				    	String email=member.getUserId()+"@163.com"; 
					    PayUpdateData ud=PayUpdateData.initialize(
								member.getPayGroupCode(), 
								member.getVirtualCard(), 
								idName, 
								cardMobile,
								idNo, 
								DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
								email,
								null,
								"01",null);//01表示用户正常  00表示用户禁用
					    PayResult payResult=IPayAPI.updateAccountData(ud);
					    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
					    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
					    }
					    logger.info("=================================认证信息修改成功==================================="); 
		    }
		}else if(memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			throw new ApplicationException(Rescode.FAIL, "该卡已认证，无需重复认证");
		}
		 Date date=new Date();
		PayResult payResult=null;
			TradeOffline tradeOffline=new TradeOffline();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(member.getGroupId());
		    tradeOffline.setPayerId(Long.parseLong(memberId));//付款者id号
		    tradeOffline.setPayerName(member.getName());//付款者姓名
		    tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());//支付方式 
		    tradeOffline.setReceiverId(null);//接收者id
		    tradeOffline.setReceiverName(null);//接收者 此处以核销录入数据
		    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Recharge.getType());//交易类型
		    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(Integer.valueOf(tranAmt)); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(Integer.valueOf(tranAmt));//实付金额
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());//交易状态
		    tradeOffline.setIsWallet(false);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMemo("微信端用户银行卡充值");
		    tradeOffline.setDetail("微信端用户银行卡充值");
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount("");//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构
		    tradeOffline.setOrderId(UtilFun.createOrderNum());
		    
		    switch (payType) {
			case "1":
				tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.CONSUMPTION_VIRTUAL));
				tradeOfflineMapper.insertSelective(tradeOffline);
				break;
			case "2":
				ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(member.getGroupId(), new Date());
	        	 ActivityUnroutineRule activityUnroutineRule=activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(
	        			 activityUnroutine.getActivityId(), Integer.valueOf(tranAmt),(byte)ActivityEnum.BackMoneyMode.Percentage.getType());
	        	 tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
	        	 tradeOfflineMapper.insertSelective(tradeOffline);
	        	 if(activityUnroutineRule!=null){
	        		 BigDecimal a1 = new BigDecimal(tranAmt);
		    	     BigDecimal a2 = new BigDecimal(activityUnroutineRule.getFaceValue());//折扣
		    		 BigDecimal a3=a1.multiply(a2);
		    		 BigDecimal bb3 = new BigDecimal(10000);
		    		 BigDecimal result =a3.divide(bb3, 2);  
	        		 TradeOffline rradeOffline1=recordRecharge(member, result.intValue(), tradeOffline.getId(), activityUnroutine.getActivityId(),UtilFun.createOrderNum());
	        		 tradeOfflineMapper.insertSelective(rradeOffline1);
	        	 }
				break;
			case "3":
				 ActivityUnroutine activity = activityUnroutineMapper.getCurrentRechargeActivite(member.getGroupId(), new Date());
	        	 ActivityUnroutineRule activityU=activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(
	        			 activity.getActivityId(), Integer.valueOf(tranAmt),(byte)ActivityEnum.BackMoneyMode.FiexedAmount.getType());
	        	 tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
	        	 tradeOfflineMapper.insertSelective(tradeOffline);
	        	 if(activityU!=null){
	        		 TradeOffline rradeOffline2=recordRecharge(member, activityU.getFaceValue(), tradeOffline.getId(), activity.getActivityId(),UtilFun.createOrderNum());
	        		 tradeOfflineMapper.insertSelective(rradeOffline2);
	        		 }
				break;
			default:
				break;
			}
		    
		    PayQuickPaymentRecharge payQuickPaymentRecharge=PayQuickPaymentRecharge.initialize(
				member.getPayGroupCode(), 
				member.getVirtualCard(), 
				tranAmt,
				bankCode, 
				"156",
				idName,
				cardNum,
				idNo, 
				cardMobile, 
				"快捷绑卡", 
				DateUtil.fomatDate(date,DateUtil.sdfTimes),
				tradeOffline.getPayOrderid(),
				"1",  
				tradeOffline.getPayOrderid(), 
				cvnStr,Ip);
		//发送
		 payResult = IPayAPI.userQuickPaymentRecharge(payQuickPaymentRecharge);
	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		
		Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		Const.CacheMap.put(Const.cardNum_CODE+memberId, cardNum);
		Const.CacheMap.put(Const.bankCode_CODE+memberId, bankCode);
		return param;
	}
	
	   
		public Map<String, Object> insertBankCardVefityConsumption(String memberId,String tranAmt, String bankCode,String cardNum,
						String idName,String idNo,String cardMobile,
						String cardCvn,String cardExpdate,String Ip,String orgOrderNumId) throws ApplicationException{
			Map<String,Object> param=new HashMap<String,Object>();
			Member member = memberMapper.queryGroup(Long.parseLong(memberId));
			if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
			}
			//校验卡是否支持绑定 提高绑卡成功率  
			Map<String, String> mapCardNum=IPayAPI.queryCardCodeNew(cardNum);
			if(!mapCardNum.get("Rcd").equals("0000")){
			throw new ApplicationException(Rescode.FAIL, "该卡暂不支持快捷绑定,请换张卡再试");
			}
			if(!mapCardNum.get("InsCd").equals(bankCode)){
			throw new ApplicationException(Rescode.FAIL, "您输入的卡号是"+mapCardNum.get("Cnm"));
			}
			MemberCard memberCardName=memberCardMapper.selectByPrimaryName(Long.parseLong(memberId));
			if(memberCardName!=null&&!memberCardName.getIdName().equals(idName)){
			throw new ApplicationException(Rescode.FAIL, "此卡认证信息与初次认证信息不一致");
			}
			//验证该卡是否绑定过
			MemberCard memberCard =  memberCardMapper.selectOneSuccessByMemberId(Long.parseLong(memberId),cardNum,bankCode,BizEnum.BindCardType.QuickPayCard.getType());
			int cardType=BizEnum.CardType.DebitCard.getType();
			String cvnStr=null;
			//此处调用绑卡接口
			if(Tools.notEmpty(cardCvn)&&Tools.notEmpty(cardExpdate)){
			cardType=BizEnum.CardType.CreditCard.getType();
			cvnStr=cardCvn+";"+cardExpdate;
			}
			if(memberCard==null){
			MemberCard record = new MemberCard();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setMemberId(Long.parseLong(memberId));
			record.setBankIntegral(bankCode);
			record.setCardNum(cardNum);
			record.setIdName(idName);
			record.setIdNo(idNo);
			record.setCardMobile(cardMobile);
			record.setCardType(cardType); 
			record.setCardCvn(cardCvn);
			record.setCardExpdate(cardExpdate);
			record.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
			record.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
			record.setBankZone(null);//开户地区
			bankDesc(record, bankCode); 
			memberCardMapper.insert(record);
			if(member.getIdNo().equals("000000000000000000")|| member.getApproveStatus() == BizEnum.ApproveStatus.UnVerify.getType()){
			member.setIdNo(idNo);
			member.setName(idName);
			member.setApproveStatus(BizEnum.ApproveStatus.Verified.getType());
			memberMapper.updateByPrimaryKeySelective(member);
			String email=member.getUserId()+"@163.com"; 
			PayUpdateData ud=PayUpdateData.initialize(
					member.getPayGroupCode(), 
					member.getVirtualCard(), 
					idName, 
					cardMobile,
					idNo, 
					DateUtil.fomatDate(new Date(),DateUtil.sdfTimes), 
					email,
					null,
					"01",null);//01表示用户正常  00表示用户禁用
			PayResult payResult=IPayAPI.updateAccountData(ud);
			if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
				throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
			}
			logger.info("=================================认证信息修改成功==================================="); 
			}
			}else if(memberCard.getCardStatus().equals(BizEnum.CardStatus.Verified.getType())){ 
			throw new ApplicationException(Rescode.FAIL, "该卡已认证，无需重复认证");
			}
			Date date=new Date();
			PayResult payResult=null;
			String orgOrderNum = UtilFun.createOrderNum();
			
			//查询是否有该笔订单记录
			TradeOffline record=tradeOfflineMapper.selectByOrderIdStatus(orgOrderNumId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());        
			if(record!=null){
			  record.setMemo("银行卡快捷支付消费购买");
			  record.setDetail("银行卡快捷支付消费购买");//详情
			  record.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
			  record.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
			  record.setPayOrderid(orgOrderNum); 
			 tradeOfflineMapper.updateByPrimaryKeySelective(record);
				PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
			  		member.getPayGroupCode(), 
						member.getVirtualCard(), 
						tranAmt,
						bankCode, 
						"156",
						idName,
						cardNum,
						idNo, 
						cardMobile, 
						"快捷绑卡消费", 
						DateUtil.fomatDate(date,DateUtil.sdfTimes),
						orgOrderNum,
						"1", 
						orgOrderNum, 
						cvnStr,Ip);
			  payResult =IPayAPI.userQuickPayment(payQuickPaymentPay);
			  if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
			  	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
			  }   }
			
			Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
			Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
			Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
			Const.CacheMap.put(Const.cardNum_CODE+memberId, cardNum);
			Const.CacheMap.put(Const.bankCode_CODE+memberId, bankCode);
			return param;
			}
	
	
	
	
	@Override
	public Map<String, Object> updatebankcardverifysubmit(String memberId, String code, String ip)
			throws ApplicationException {
		String SysOrderNum=Const.CacheMap.get(Const.SysOrderNum_CODE+memberId);
		String paySign=Const.CacheMap.get(Const.PaySign_CODE+memberId);
		String ThirdOrderNum=Const.CacheMap.get(Const.ThirdOrderNum_CODE+memberId);
		String cardNum=Const.CacheMap.get(Const.cardNum_CODE+memberId);
		String bankCode=Const.CacheMap.get(Const.bankCode_CODE+memberId);
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(Tools.isEmpty(SysOrderNum)||Tools.isEmpty(paySign)||Tools.isEmpty(ThirdOrderNum)){
			throw new ApplicationException(Rescode.FAIL, "未填写资料信息");
		}
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectOneSuccessByMemberId(Long.parseLong(memberId),cardNum,bankCode,BizEnum.BindCardType.QuickPayCard.getType());
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "卡信息不存在");
		}
		if(memberCard.getCardStatus().equals(BizEnum.CardStatus.UnVerify.getType())){
			memberCard.setCardStatus(BizEnum.CardStatus.Verified.getType()); 
			memberCardMapper.updateByPrimaryKey(memberCard);
		}
		String orgOrderNum = UtilFun.createOrderNum();
		PayQuickPaymentRechargeSubmit qprs=PayQuickPaymentRechargeSubmit.initialize(member.getPayGroupCode(), member.getVirtualCard(), SysOrderNum, null, code,
				ThirdOrderNum, paySign, memberCard.getCardMobile(), memberCard.getCardNum(), orgOrderNum, ip);
		PayResult payResult=IPayAPI.userQuickPaymentRechargeSubmit(qprs);
		if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
	    }
		return null;
	}
	
	
	@Override
	public Map<String, Object> updateExistCardsubmit(String memberId,  String ip, String cardId,String tranAmt,String payType,String orgOrderNumId)
			throws ApplicationException {
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		String cvnStr=null;
		//此处调用绑卡接口
		if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){ 
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}
		PayResult payResult=null;
		Date date=new Date();
			TradeOffline tradeOffline=new TradeOffline();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(member.getGroupId());
		    tradeOffline.setPayerId(Long.parseLong(memberId));//付款者id号
		    tradeOffline.setPayerName(member.getName());//付款者姓名
		    tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());//支付方式 生成订单支付方式未知
		    tradeOffline.setReceiverId(null);//接收者id
		    tradeOffline.setReceiverName(null);//接收者 此处以核销录入数据
		    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Recharge.getType());//交易类型
		    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(Integer.valueOf(tranAmt)); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(Integer.valueOf(tranAmt));//实付金额
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());//交易状态
		    tradeOffline.setIsWallet(false);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMemo("充值");
		    tradeOffline.setDetail("用户银行快捷卡充值");
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount("");//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setOrderId(UtilFun.createOrderNum());
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构
		    switch (payType) {
			case "1":
				
				tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.CONSUMPTION_VIRTUAL));
				tradeOfflineMapper.insertSelective(tradeOffline);
				break;
			case "2":
				ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(member.getGroupId(), new Date());
	        	 ActivityUnroutineRule activityUnroutineRule=activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(
	        			 activityUnroutine.getActivityId(), Integer.valueOf(tranAmt),(byte)ActivityEnum.BackMoneyMode.Percentage.getType());
	        	 tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
	        	 tradeOfflineMapper.insertSelective(tradeOffline);
	        	 if(activityUnroutineRule!=null){
	        		 BigDecimal a1 = new BigDecimal(tranAmt);
		    	     BigDecimal a2 = new BigDecimal(activityUnroutineRule.getFaceValue());//折扣
		    		 BigDecimal a3=a1.multiply(a2);
		    		 BigDecimal bb3 = new BigDecimal(10000);
		    		 BigDecimal result =a3.divide(bb3, 2);  
	        		 TradeOffline rradeOffline1=recordRecharge(member, result.intValue(), tradeOffline.getId(), activityUnroutine.getActivityId(),UtilFun.createOrderNum());
	        		 tradeOfflineMapper.insertSelective(rradeOffline1);
	        	 }
				break;
			case "3":
				 ActivityUnroutine activity = activityUnroutineMapper.getCurrentRechargeActivite(member.getGroupId(), new Date());
	        	 ActivityUnroutineRule activityU=activityUnroutineRuleMapper.selectActivityUnroutineRuleInfo(
	        			 activity.getActivityId(), Integer.valueOf(tranAmt),(byte)ActivityEnum.BackMoneyMode.FiexedAmount.getType());
	        	 tradeOffline.setPayOrderid(UtilFun.createOrderNum(Const.SEND_RECHARGE));
	        	 tradeOfflineMapper.insertSelective(tradeOffline);
	        	 if(activityU!=null){
	        		 TradeOffline rradeOffline2=recordRecharge(member, activityU.getFaceValue(), tradeOffline.getId(), activity.getActivityId(),UtilFun.createOrderNum());
	        		 tradeOfflineMapper.insertSelective(rradeOffline2);
	        		 }
				break;
			default:
				break;
			}
			PayQuickPaymentRecharge payQuickPaymentRecharge=PayQuickPaymentRecharge.initialize(
					member.getPayGroupCode(), 
					member.getVirtualCard(), 
					tranAmt,
					memberCard.getBankIntegral(), 
					"156",
					memberCard.getIdName(),
					memberCard.getCardNum(),
					memberCard.getIdNo(), 
					memberCard.getCardMobile(), 
					"快捷绑卡", 
					DateUtil.fomatDate(date,DateUtil.sdfTimes),
					tradeOffline.getPayOrderid(),
					"1", 
					tradeOffline.getPayOrderid(), 
					cvnStr,ip);
		    payResult = IPayAPI.userQuickPaymentRecharge(payQuickPaymentRecharge);
		    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
		    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
		    }
		
		Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		Const.CacheMap.put(Const.cardNum_CODE+memberId, memberCard.getCardNum());
		Const.CacheMap.put(Const.bankCode_CODE+memberId, memberCard.getBankIntegral());
		return param;
	}

	
	@Override
	public Map<String, Object> updateExistCardsubmitConsumption(String memberId,  String ip, String cardId,String tranAmt,String orgOrderNumId)
			throws ApplicationException {
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		String cvnStr=null;
		//此处调用绑卡接口
		if(memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())){ 
			cvnStr=memberCard.getCardCvn()+";"+memberCard.getCardExpdate();
		}
		PayResult payResult=null;
		Date date=new Date();
		 //查询是否有该笔订单记录
	       TradeOffline record=tradeOfflineMapper.selectByOrderIdStatus(orgOrderNumId,(byte)BizEnum.TransactionStatus.WaitingForPay.getType());        
	       if(record!=null){
	    	   String orgOrderNum = record.getOrderId();
		  	    	record.setMemo("银行卡快捷支付消费购买");
		  	    	    record.setDetail("银行卡快捷支付消费购买");//详情
		  	    	    record.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
		  	    	    record.setPayType((byte)BizEnum.PaymentType.NetBankCardQuick.getType());
		  	    	    record.setPayOrderid(orgOrderNum); 
		 		        tradeOfflineMapper.updateByPrimaryKeySelective(record);
			  	    	 PayQuickPaymentPay payQuickPaymentPay=PayQuickPaymentPay.initialize(
			      	    		member.getPayGroupCode(), 
			      				member.getVirtualCard(), 
			      				record.getOrderAmount()+"",
			      				memberCard.getBankIntegral(), 
			      				"156",
			      				memberCard.getIdName(),
								memberCard.getCardNum(),
								memberCard.getIdNo(), 
								memberCard.getCardMobile(), 
			      				"快捷绑卡消费", 
			      				DateUtil.fomatDate(date,DateUtil.sdfTimes),
			      				orgOrderNum,
			      				"1", 
			      				orgOrderNum, 
			      				cvnStr,ip); 
			  	    	payResult =IPayAPI.userQuickPayment(payQuickPaymentPay);
			      	    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
			      	    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
			      	    }
		  	       }else{
			    	   throw new ApplicationException(Rescode.FAIL,"未查询到未支付的订单");
		}
		
		Const.CacheMap.put(Const.SysOrderNum_CODE+memberId, payResult.getSysOrderNum());
		Const.CacheMap.put(Const.PaySign_CODE+memberId, payResult.getPaySign());
		Const.CacheMap.put(Const.ThirdOrderNum_CODE+memberId, payResult.getThirdOrderId());
		Const.CacheMap.put(Const.cardNum_CODE+memberId, memberCard.getCardNum());
		Const.CacheMap.put(Const.bankCode_CODE+memberId, memberCard.getBankIntegral());
		return param;
	}
	
	
	
	
	public void bankDesc(MemberCard record,String bankCode) { 
		switch (bankCode) {
		case "0801020000":
			record.setIssuerBankName("工商银行");
			break;
		case "0801030000":
			record.setIssuerBankName("农业银行");
			break;
		case "0801040000":
			record.setIssuerBankName("中国银行");
			break;
		case "0801050000":
			record.setIssuerBankName("建设银行");
			break;
		case "0801000000":
			record.setIssuerBankName("邮政储蓄银行");
			break;
		case "0804100000":
			record.setIssuerBankName("平安银行");
			break;
		case "0803050000":
			record.setIssuerBankName("民生银行");
			break;
		case "0803030000":
			record.setIssuerBankName("光大银行");
			break;
		case "0803060000":
			record.setIssuerBankName("广发银行");
			break;
		case "0863020000"://0803020000 //
			record.setIssuerBankName("中信银行");
			break;
		case "0803090000":
			record.setIssuerBankName("兴业银行");
			break;
		case "0803040000":
			record.setIssuerBankName("华夏银行");
			break;
		case "0803080000":
			record.setIssuerBankName("招商银行");
			break;
		case "0803100000":
			record.setIssuerBankName("浦发银行");
			break;
		case "0803010000":
			record.setIssuerBankName("交通银行");
			break;
		case "0804031000":
			record.setIssuerBankName("北京银行");
			break;
		case "0804012900":
			record.setIssuerBankName("上海银行");
			break;
		case "0804023930":
			record.setIssuerBankName("厦门银行");
			break;	
		default:
			record.setIssuerBankName(null);
			break;
		}
	}
	
	

	//转账
	public Map<String, Object> insertUserTransfer(String memberId, String phone,String toMemberId,Integer amount,String password,Integer fee,String rootHomeUrl) throws ApplicationException{
		String orgOrderNum = UtilFun.createOrderNum();
		StringBuffer sb = new StringBuffer();
		Map<String,Object> param=new HashMap<String,Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		Member toMember =null; 
		//微信端通过对方ID查询
		if(Tools.notEmpty(phone)){
			toMember=memberMapper.selectByPrimaryPhone(member.getGroupId(),phone,null);
		}else{
			toMember=memberMapper.queryGroup(Long.parseLong(toMemberId));
			
		}
		//兼容老用户
				if(member.getTradePassword().equals("888888")){
					member.setTradePassword(AES.AESEncode(Const.AceKey, password));  
				}else{
					if (!AES.AESEncode(Const.AceKey, password).equals(member.getTradePassword())) {
						throw new ApplicationException(Rescode.FAIL, "支付密码错误");
					}
				}
		Date date=new Date();
		PayTransferResult payTransferResult = walletService.updateConsumptionTransfer(member.getVirtualCard(), toMember.getVirtualCard(), toMember.getName(), member.getPayGroupCode(), 
				member.getUserId(), toMember.getUserId(), amount, fee, orgOrderNum, password);
		
		if(!payTransferResult.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL,payTransferResult.getMsgTxt());
		}
		//  Integer balance=member.getBalance()-Integer.valueOf(payTransferResult.getActualAt());
	    //  member.setBalance(balance);
		//  memberMapper.updateByPrimaryKeySelective(member);
		
		Integer balanceTo=null;
		if(toMember.getBalance()==null){
			balanceTo=amount; 
		}else{
			balanceTo=toMember.getBalance()+amount;
		}
		//插入线下交易表
		String OrgOrderNum = UtilFun.createOrderNum();
		TradeOffline record = new TradeOffline();
		record.setGmtCreate(date);
        record.setGmtModified(date);
        record.setGroupId(member.getGroupId());
        record.setOrderId(OrgOrderNum); 
        record.setPayerId(member.getId());//会员id
        record.setPayerName(member.getName());
        record.setPayerType((byte)CommonEnum.UserType.User.getType());
        record.setReceiverId(toMember.getId()+"");//接收者id
        record.setReceiverName(toMember.getName());//接收者
	    record.setReceiverType((byte)CommonEnum.UserType.User.getType());
        record.setTransactionType((byte)BizEnum.TransactionType.Transfer.getType());
        record.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
        record.setOrderAmount(amount); 
        record.setDiscountAmount(0);//折扣金额
        record.setRealAmount(amount);//实付金额
        record.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
        record.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
        record.setIsWallet(true);
        record.setMemo("用户钱包转账");
		sb.append("支付接口返回结果:orderId=").append(payTransferResult.getOrderId()).
		append("&ActualAt=").append(payTransferResult.getActualAt()).
		append("&FeeAt=").append(payTransferResult.getFeeAt()).
		append("&MsgTxt=").append(payTransferResult.getMsgTxt());
        record.setDetail(sb.toString());
        record.setTermSerial(null);
        record.setMerchantNo(null);//商户号
        record.setTerminalNo(null);//商户终端号
        record.setTransNo(null); //交易流水号
        record.setTransOrderNo(null);//交易机构订单号
        record.setPayAccount(member.getVirtualCard());//支付卡号
        record.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
        record.setCrcodeStr(null); 
        record.setOldOrderId(null); 
        record.setDividableAmount(0);//可分润金额
        record.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        record.setPayOrderid(orgOrderNum);
        record.setPayBakOrderid(payTransferResult.getOrderId());
        record.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());//入网机构
        record.setFee(fee); 
        tradeOfflineMapper.insertSelective(record);
        //屏蔽此代码
//      param.put("balance", balance);
        param.put("orderId", OrgOrderNum);
        param.put("feeAt", payTransferResult.getFeeAt());
        //发送模板消息用
//        param.put("tradeOffline", record);
        param.put("groupId", member.getGroupId());
        param.put("balance", balanceTo);//当前余额
        param.put("orderId", OrgOrderNum);//当前余额
        param.put("virtualCard", toMember.getPhone());//接收账户
        
        try { 
        	templateMailSendService.sendTemplate(record,  BizEnum.WebTemplateType.template9.getType(), record.getPayerId(),
        			record.getGroupId(), BizEnum.PaymentType.Wallet.getType(),rootHomeUrl);
            templateMailSendService.sendTemplate(record,  BizEnum.WebTemplateType.template13.getType(), toMember.getId(),
            		record.getGroupId(), BizEnum.PaymentType.Wallet.getType(),rootHomeUrl);
		} catch (Exception e) {
			 logger.info("模板消息发送失败"+e); 
		}
		return param;
	}

	//账单列表
	public Map<String, Object> getTradeDetailList(String memberId, Integer offOrOnLine,Integer pageNo,Integer pageSize) throws Exception{
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (offOrOnLine !=1 && offOrOnLine != 2) {
			throw new ApplicationException(Rescode.FAIL, "offOrOnLine 参数非法！");
		}
		if (pageNo == null) {
			throw new ApplicationException(Rescode.FAIL,"pageNo 不能为空！");
		}
		if (pageSize == null) {
			throw new ApplicationException(Rescode.FAIL,"pageSize 不能为空！");
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String,Object>> tradeList = new ArrayList<Map<String, Object>>();

		if(offOrOnLine == 1 || offOrOnLine == 2){//
			List<TradeOffline> tradeOfflines = tradeOfflineMapper.selectAppTradeList(Long.parseLong(memberId),offOrOnLine,(pageNo-1)*pageSize,pageSize);
			for(TradeOffline tradeOffline:tradeOfflines){
				Map<String, Object> tradeOfflineMap = new HashMap<String, Object>();
				tradeOfflineMap.put("order_id",tradeOffline.getOrderId());
				tradeOfflineMap.put("order_time",DateUtil.fomatDate(tradeOffline.getGmtCreate(),DateUtil.sdfTime));
				tradeOfflineMap.put("money",String.valueOf(tradeOffline.getRealAmount()/100));
				tradeOfflineMap.put("trade_type", BizEnum.TransactionType.fromType(tradeOffline.getTransactionType()).getName());
				tradeOfflineMap.put("status", BizEnum.TransactionStatus.fromType(tradeOffline.getTransactionStatus()).getName());
				tradeList.add(tradeOfflineMap);
			}
		}
		if(tradeList.size()>0) {
			map.put("trade_list", tradeList);
		}

		return map;
	}

	//订单评价
	//@Transactional(rollbackFor = {RuntimeException.class,Exception.class},readOnly = false)insertServiceGoodOrderComment insertOrderComment
	public Map<String, Object> insertServiceGoodOrderComment(String memberId,String orderId,Integer isDisplay, Integer commentLevel,String commentContent,String picUrls) throws Exception{
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (Tools.isEmpty(orderId)) {
			throw new ApplicationException(Rescode.FAIL, "orderId 不能为空！");
		}
		if (isDisplay == null) {
			throw new ApplicationException(Rescode.FAIL,"isDisplay 不能为空！");
		}
		if (commentLevel == null) {
			throw new ApplicationException(Rescode.FAIL,"commentLevel 不能为空！");
		}
		if (Tools.isEmpty(commentContent)) {
			throw new ApplicationException(Rescode.FAIL, "commentContent 不能为空！");
		}

		//取得评价门店id(服务商品暂按最后一次的核销门店为评价对象)
		Long shopId = orderServiceGoodDetailMapper.getLastVerifyShopIdByOrderId(Long.parseLong(orderId));
		OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(Long.parseLong(orderId));
		Member member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));

		Map<String, Object> map = new HashMap<String, Object>();
        //插入评价内容
		MallGoodComment mallGoodComment = new MallGoodComment();
		mallGoodComment.setGmtCreate(new Date());
		mallGoodComment.setGmtModified(new Date());
		mallGoodComment.setCreaterId(Long.parseLong(memberId));
		mallGoodComment.setGoodId(orderServiceGood.getGoodId());
		mallGoodComment.setIsCryptonym(isDisplay==1?Boolean.TRUE:Boolean.FALSE);
		mallGoodComment.setCommentLevel(commentLevel);
		mallGoodComment.setContent(commentContent);
		mallGoodComment.setPicUrls(picUrls);
		mallGoodComment.setOrderId(Long.parseLong(orderId));
		mallGoodComment.setCommentType(BizEnum.CommentType.ServiceGood.getType());
		mallGoodComment.setGroupId(member.getGroupId());
		mallGoodComment.setAuditStatus(1);
		mallGoodComment.setShopId(shopId);
//        int result = mallGoodCommentMapper.insertGoodComment(mallGoodComment);
        mallGoodCommentMapper.insert(mallGoodComment);


		/*result = activityUnroutineService.insertUnroutineSend(Long.parseLong(memberId),Long.parseLong(orderId),
				ActivityEnum.ActivityPlatformType.OnLine.getType(),map);
				*/

		//更新订单状态
		OrderServiceGood updateRecord = new OrderServiceGood();
		updateRecord.setId(Long.parseLong(orderId));
		updateRecord.setOrderStatus(BizEnum.ServiceOrderStatus.OrderFinished.getType());
		updateRecord.setGmtModified(new Date());
		orderServiceGoodMapper.updateByPrimaryKeySelective(updateRecord);

		return map;
	}

	//邀请会员参与活动
	public Map<String, Object> insertInviteMember(Long groupId,Long memberId, Long newMemberId) throws Exception{
		logger.info("----邀请会员参与活动----");
		Map<String, Object> map = new HashMap<String, Object>();
		int result = 0;
		//取得活动规则
		ActivityRoutineRegister register = activityRoutineRegisterMapper.selectRegisterActivityByGroupId(groupId);
		register.setGroupId(groupId);
		if(register == null)
			return map;

		//被邀请人
		if(register.getInviteeSendType()==ActivityEnum.ActivitySendType.Coupon.getType()){
			try {
				result = couponUserService.sendOneMemberCoupon(newMemberId, register.getInviteeCouponId(),
						register.getActivityId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "被邀请赠送",null);
			}catch (Exception ae){
				logger.error(ae);
				result = 0;
			}
			if(result==1) {
				map.put("invitee_coupon_id", register.getInviteeCouponId());
				map.put("invitee_coupon_name", register.getInviteeCouponName());
			}
		}else if(register.getInviteeSendType()==ActivityEnum.ActivitySendType.RedPackage.getType()){
			try {
				result = redPackageUserService.sendOneMemberRedPackage(newMemberId,register.getInviteeRedpackageId(),
						register.getActivityId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "被邀请赠送",null);
			}catch (Exception ae){
				logger.error(ae);
				result = 0;
			}
			if(result==1){
				map.put("invitee_redpackage_id",register.getInviteeRedpackageId());
				map.put("invitee_redpackage_name",register.getInviteeRedpackageName());
			}
		}else if(register.getInviteeSendType() == ActivityEnum.ActivitySendType.Bonus.getType()){
			try {
				BonusSendLog bonusSendLog_3 = BonusSendLog.build(register.getGroupId(),newMemberId, ActivityEnum.BonusSendType.routineActivityRegister.getType(),
						Integer.parseInt(String.valueOf(register.getInviteeIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"被邀请赠送",register.getActivityId());
				result = bonusService.sendOneMemberBonus(bonusSendLog_3);
			}catch (Exception ae){
				logger.error(ae);
				result = 0;
			}
            if(result==1){
//                map.put("invitee_redpackage_id",register.getInviteeRedpackageId());
//                map.put("invitee_redpackage_name",register.getInviteeRedpackageName());
            }
		}
		//邀请人
		if(register.getInviterSendType()==ActivityEnum.ActivitySendType.Coupon.getType()){
			try {
				result = couponUserService.sendOneMemberCoupon(memberId, register.getInviterCouponId(),
						register.getActivityId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "邀请赠送",null);
			}catch (Exception ae){
				logger.error(ae);
				//throw ae;
				result = 0;
			}
			if(result==1) {
				map.put("inviter_coupon_id", register.getInviterCouponId());
				map.put("inviter_coupon_name", register.getInviterCouponName());
			}
		}else if(register.getInviterSendType()==ActivityEnum.ActivitySendType.RedPackage.getType()){
			try {
				result = redPackageUserService.sendOneMemberRedPackage(memberId, register.getInviterRedpackageId(),
						register.getActivityId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "邀请赠送",null);
			}catch (Exception ae){
				logger.error(ae);
				result = 0;
			}
			if(result==1){
				map.put("inviter_redpackage_id",register.getInviterRedpackageId());
				map.put("inviter_redpackage_name",register.getInviterRedpackageName());
			}
		}else if(register.getInviterSendType() == ActivityEnum.ActivitySendType.Bonus.getType()){
            try {
                BonusSendLog bonusSendLog_3 = BonusSendLog.build(register.getGroupId(),memberId, ActivityEnum.BonusSendType.routineActivityRegister.getType(),
                        Integer.parseInt(String.valueOf(register.getInviterIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"邀请赠送",register.getActivityId());
                result = bonusService.sendOneMemberBonus(bonusSendLog_3);
            }catch (Exception ae){
                logger.error(ae);
                result = 0;
            }
            if(result==1){
//                map.put("invitee_redpackage_id",register.getInviteeRedpackageId());
//                map.put("invitee_redpackage_name",register.getInviteeRedpackageName());
            }
        }

		return map;
	}

	//红包领取
	@Override
	public Map<String, Object> insertRedpackageUser(String memberId, String redpackageUserId) throws Exception {
		int result = 0;
		Map<String, Object> map = new HashMap<String, Object>();
		result = activityRedPackageService.insertRedpackageUser(memberId,redpackageUserId);
		map.put("amount", result);
		return map;
	}

	//添加商品到购物车
	public int insertMallCart(String memberId, String goodsId,Integer number,Long specId, Long shareMemberId)throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (Tools.isEmpty(goodsId)) {
			throw new ApplicationException(Rescode.FAIL, "goodsId 不能为空！");
		}

		Date date = new Date();
		MallCart mallCart;
		if(specId != null) {
			mallCart = mallCartMapper.selectByMemberIdGoodSpec(Long.parseLong(memberId), specId);
		} else {
			mallCart = mallCartMapper.selectByMemberIdAndGoodsId(Long.parseLong(memberId),Long.parseLong(goodsId));
		}

		if(mallCart != null) {
			mallCart.setGoodNumber(mallCart.getGoodNumber() + number);
			mallCart.setGmtModified(date);
			mallCartMapper.updateByPrimaryKeySelective(mallCart);
		} else {
			mallCart = new MallCart();
			mallCart.setGmtCreate(date);
			mallCart.setGmtModified(date);
			mallCart.setMemberId(Long.parseLong(memberId));
			mallCart.setGoodId(Long.parseLong(goodsId));
			mallCart.setGoodNumber(number);
			mallCart.setSpecId(specId);
			mallCart.setShareMemberId(shareMemberId);
			result = mallCartMapper.insertSelective(mallCart);
		}
		return result;
	}

	//移除购物车中商品
	public int deleteMallCart(String memberId, String goodsId)throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (Tools.isEmpty(goodsId)) {
			throw new ApplicationException(Rescode.FAIL, "goodsId 不能为空！");
		}

		result = mallCartMapper.deleteByMemberIdAndGoodId(Long.parseLong(memberId),Long.parseLong(goodsId));

		return result;
	}

	//获取购物车
	public List<Map<String, Object>> getMallCart(Long memberId) {
	   	Member member = memberMapper.selectByPrimaryKey(memberId);

		List<Map<String, Object>> cartList =  mallCartMapper.selectByMemberId2(memberId);
		for(Map<String, Object> cart : cartList) {
			Long specId = (Long) cart.get("spec_id");
			if(specId != null) {
				MallEntityGoodSpec mallEntityGoodSpec = mallEntityGoodSpecMapper.selectByPrimaryKey(specId);
				if(mallEntityGoodSpec != null) {
					cart.replace("goodsPromotionPrice", mallEntityGoodSpec.getPrice());
					cart.replace("goodsPromotionPrice2", mallEntityGoodSpec.getPrice2());
				}
			}
			if(member.getWalletStatus()==0) {
				cart.put("realPrice", cart.get("goodsPromotionPrice2"));
				cart.replace("goodsSalePrice", cart.get("goodsPromotionPrice2"));
			} else {
				cart.put("realPrice", cart.get("goodsPromotionPrice"));
				cart.replace("goodsSalePrice", cart.get("goodsPromotionPrice"));
			}
		}
		return cartList;
	}

    //保存我的地址信息
	public int saveMyAddress(String memberId, Integer defaultSelect,String addressMobilePhone,
							 String addressCustomerName,String addressCity,String addressArea,Long addressId) throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if(defaultSelect == null || (defaultSelect != 0 && defaultSelect != 1)) {
			throw new ApplicationException(Rescode.FAIL, "defaultSelect 值不对！");
		}

		int count = 0;
		if(defaultSelect == 1) {
			//int count = memberAddressMapper.selectDefaultCount(Long.parseLong(memberId));
			//if(count >0)
			//	throw new ApplicationException(Rescode.FAIL, "缺省地址已经存在！");
			count = memberAddressMapper.updateRecordIsDefault(Long.parseLong(memberId));
		}

		//新增
        if(addressId ==null){
            MemberAddress record = new MemberAddress();
            record.setMemberId(Long.parseLong(memberId));
            record.setCustomerName(addressCustomerName);
            record.setPhone(addressMobilePhone);
            record.setCity(addressCity);
            record.setArea(addressArea);
            if(defaultSelect != 1) {
				MemberAddress memberAddress = memberAddressMapper.selectDefaultRecordByMemberId(Long.parseLong(memberId));
				if(memberAddress == null) {
					defaultSelect = 1;
				}
			}
            record.setIsDefault(defaultSelect==1?Boolean.TRUE:Boolean.FALSE);
            record.setStatus(1);
            result = memberAddressMapper.insert(record);
		}else{
			MemberAddress record = new MemberAddress();
			record.setMemberId(Long.parseLong(memberId));
			record.setCustomerName(addressCustomerName);
			record.setPhone(addressMobilePhone);
			record.setCity(addressCity);
			record.setArea(addressArea);
			record.setIsDefault(defaultSelect==1?Boolean.TRUE:Boolean.FALSE);
			record.setId(addressId);
			result = memberAddressMapper.updateByPrimaryKeySelective(record);
		}

		return result;
	}

	//获取地址列表
	public Map<String, Object> getMyAddressList(String memberId) throws Exception{
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<MemberAddress> memberAddressList = memberAddressMapper.selectByMemberId(Long.parseLong(memberId));
		List<Map<String,Object>> addressList = new ArrayList<Map<String, Object>>();
		for(MemberAddress memberAddress:memberAddressList){
			Map<String, Object> detail = new HashMap<String, Object>();
			detail.put("addressId",memberAddress.getId());
			detail.put("defaultSelect",memberAddress.getIsDefault()?1:0);
			detail.put("addressCustomerName",memberAddress.getCustomerName());
			detail.put("addressArea",memberAddress.getArea());
			detail.put("addressCity",memberAddress.getCity());
			detail.put("addressMobilePhone",memberAddress.getPhone());
			addressList.add(detail);
		}
		if(addressList.size()>0) {
			map.put("addressList", addressList);
		}
		return map;

	}

	//获取缺省地址
	public Map<String, Object> getDefaultAddress(String memberId) throws Exception{
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		MemberAddress record = memberAddressMapper.selectDefaultRecordByMemberId(Long.parseLong(memberId));
		if(record ==null)
			return map;

		map.put("addressId",record.getId());
		map.put("defaultSelect",record.getIsDefault()?1:0);
		map.put("addressCustomerName",record.getCustomerName());
		map.put("addressArea",record.getArea());
		map.put("addressCity",record.getCity());
		map.put("addressMobilePhone",record.getPhone());

        return map;
	}

	//删除地址
	public int deleteMyAddress(String memberId,Long addressId) throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (addressId == null) {
			throw new ApplicationException(Rescode.FAIL, "addressId 不能为空！");
		}
		MemberAddress record = new MemberAddress();
		record.setId(addressId);
		record.setStatus(0);
		result = memberAddressMapper.updateByPrimaryKeySelective(record);

		return result;
	}

	//设置默认地址
	public int setDefaultMyAddress(String memberId,Long addressId) throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (addressId == null) {
			throw new ApplicationException(Rescode.FAIL, "addressId 不能为空！");
		}
		MemberAddress record = new MemberAddress();
		record.setId(addressId);
		record.setIsDefault(true);
		result = memberAddressMapper.updateByPrimaryKeySelective(record);

		return result;
	}


	public Response addQuickRechargeMemberCard(String groupId,Long memberId,String cardNum,String customerName,String mobilePhone,
			String certNo,String issuerId,Long cardId,String expdate,String cvn,String bankCodeNew){
		 Response baseResult = new Response();
		Member member=this.memberMapper.selectByPrimaryKey(memberId); 
		Group businessBase=this.groupMapper.selectByPrimaryKey(member.getGroupId()); 
		if(businessBase==null || !businessBase.getPayGroupCode().equals(groupId) ){
			baseResult.setStatus(false);
			baseResult.setMessage("参数不能为空");
			return baseResult;
		}
	
		/**
		 * 账户类型信息查询
		 */
		String cardTypeValue=null;
		String bankName=null;
		String cardIntegral=null;
		Map<String ,String> mapBankInfo=IPayAPI.queryCardCodeNew(cardNum);
		
		if("0000".equals(mapBankInfo.get("Rcd"))){
			cardTypeValue=mapBankInfo.get("Ctp");
			bankName=mapBankInfo.get("Cnm");
			cardIntegral=mapBankInfo.get("InsCd");
		}else if("5505".equals(mapBankInfo.get("Rcd"))){
			baseResult.setStatus(false);
			baseResult.setMessage("当前交易不支持此卡或者卡号错误");
			return baseResult;
				
		}else{
			baseResult.setStatus(false);
			baseResult.setMessage(mapBankInfo.get("Rcd")+":"+mapBankInfo.get("RDesc"));
			return baseResult;
		}

		
		//检验银行
		if(!bankName.contains(issuerId)){
			if(StringUtils.isNotBlank(bankCodeNew)&&StringUtils.isNotBlank(cardIntegral)){
				 bankCodeNew=bankCodeNew.substring(2,6);
				String bankCode=cardIntegral;
				 if(cardIntegral.length()==8){
					 bankCode=cardIntegral.substring(0,4);
				 }else{
					 bankCode=cardIntegral.substring(2,6);
				 }
				 
				 if(!bankCodeNew.equals(bankCode)){
					 baseResult.setStatus(false);
					 baseResult.setMessage("检测卡号的银行为："+bankName+",你选择的银行为:"+issuerId);
					 return baseResult;
				 }
			}else{
				 baseResult.setStatus(false);
				 baseResult.setMessage("检测卡号的银行为："+bankName+",你选择的银行为:"+issuerId);
				 return baseResult;
			}
			
		}		
				
		
		String cardAccountType= SysUtils.convertTypeValue(cardTypeValue);
		if(!cardAccountType.contains("借记")){
			if(StringUtils.isBlank(expdate)||StringUtils.isBlank(cvn)){
				 baseResult.setStatus(false);
				 baseResult.setMessage("快捷支付，银行卡为信用卡，有效期和cvn必填");
				 return baseResult;
			}
		}
		
		MemberCard record = new MemberCard();
		record.setGmtCreate(new Date());
		record.setGmtModified(new Date());
		record.setMemberId(memberId);
		record.setBankIntegral(cardIntegral);
		record.setCardNum(cardNum);
		record.setIdName(customerName);
		record.setIdNo(certNo);
		record.setCardMobile(mobilePhone);
		if(cardAccountType.contains("借记")){
			record.setCardType(BizEnum.CardType.DebitCard.getType()); 
		}else{
			record.setCardType(BizEnum.CardType.CreditCard.getType()); 
		}
		
		record.setCardCvn(cvn);
		record.setCardExpdate(expdate);
		record.setBindCardType(BizEnum.BindCardType.QuickPayCard.getType());
		record.setCardStatus(BizEnum.CardStatus.UnVerify.getType());
		record.setBankZone(null);//开户地区
		bankDesc(record, bankCodeNew); 
		Map<String,Object> map=new HashMap<String,Object>(); 
		map.put("cardMemberId", memberId);
		map.put("bindCardType", 2); 
		if(cardId!=null){
			map.put("cardId", cardId);
		}
		else{
			map.put("cardNum", cardNum);
		}
		MemberCard memberCard=this.memberCardMapper.selectByItem(map);
		if(memberCard!=null){
			record.setId(memberCard.getId());
			 memberCardMapper.updateByPrimaryKey(record);
		}else{
			 memberCardMapper.insert(record);
		}
		 if(member.getIdNo().equals("000000000000000000")){
		    	member.setIdNo(certNo);
		    	member.setName(customerName);
		    	memberMapper.updateByPrimaryKeySelective(member);
		    }
		return  baseResult.format(true,1,"快捷支付卡信息更新成功",record.getId());
	}

	public Map<String, Object> getAdvertList(String memberId,Integer advertType) throws Exception{
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (advertType != 1 && advertType != 2) {
			throw new ApplicationException(Rescode.FAIL, "advertType 值不正确！");
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<MainAdvert> mainAdvertList = mainAdvertMapper.getAdvertListByMemberId(advertType,Long.parseLong(memberId));
		List<Map<String,Object>> advertList = new ArrayList<Map<String, Object>>();
		for(MainAdvert mainAdvert:mainAdvertList){
			Map<String, Object> detail = new HashMap<String, Object>();
			detail.put("sort",mainAdvert.getSortNum());
			detail.put("advertName",mainAdvert.getAdvertName());
			detail.put("photoUrl",mainAdvert.getPhotoUrl());
			detail.put("clickUrl",mainAdvert.getClickUrl());
			detail.put("adHref",mainAdvert.getClickUrl());
			detail.put("adName",mainAdvert.getAdvertName());
			advertList.add(detail);
		}
		if(advertList.size()>0) {
			map.put("advertList", advertList);
		}
		return map;
	}
	
	
    //获取消息列表
    public Map<String, Object> getMessageList(String memberId,Integer messageType,Integer pageNo,Integer pageSize) throws Exception{
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (messageType != 20 ) {
            throw new ApplicationException(Rescode.FAIL, "messageType 值不正确！");
        }
        if (pageNo == null) {
            throw new ApplicationException(Rescode.FAIL,"pageNo 不能为空！");
        }
        if (pageSize == null) {
            throw new ApplicationException(Rescode.FAIL,"pageSize 不能为空！");
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Map<String,Object> param=new HashMap<String,Object>();
        //取得门店数据；
        param.clear();
        param.put("memberId", Long.parseLong(memberId));
        param.put("messageType", messageType);

        int sumCount = sysMessageInfoMapper.selectMemberMessageListCount(param);
        if(sumCount<=0)
            return map;

        param.put("start", pageSize*(pageNo-1));
        param.put("limit", pageSize);
        List<SysMessageOutDTO> sysMessageOutDTOList = sysMessageInfoMapper.selectMemberMessageList(param);

        List<Map<String,Object>> messageList = new ArrayList<Map<String, Object>>();

        for(SysMessageOutDTO sysMessageOutDTO:sysMessageOutDTOList){
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("id",sysMessageOutDTO.getId());
            detail.put("messageId",sysMessageOutDTO.getMessageId());
            detail.put("gmtCreate",sysMessageOutDTO.getGmtCreate());
            detail.put("hasRead",sysMessageOutDTO.getHasRead()==null?0:1);
            detail.put("memberName",sysMessageOutDTO.getMemberName());
            detail.put("memberPhone",sysMessageOutDTO.getMemberPhone());
            detail.put("memo",sysMessageOutDTO.getMemo());
            detail.put("sendFrom",sysMessageOutDTO.getSendFrom());
            detail.put("title",sysMessageOutDTO.getTitle());
            messageList.add(detail);
        }
        if(messageList.size()>0) {
            map.put("messageList", messageList);
        }
        return map;
    }

    //更新消息
    public int updateMessageById(String memberId,Integer messageId,Integer status) throws Exception{
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (messageId == null) {
            throw new ApplicationException(Rescode.FAIL, "messageId 不能为空！");
        }
        if (status != 0 && status != 1) {
            throw new ApplicationException(Rescode.FAIL, "status 值不正确！");
        }

        int result =0;
        //删除
        if(status == 0){
            result = sysMessageInfoMapper.deleteByPrimaryKey((long)messageId);
        }else if(status == 1) {//已读
            SysMessageInfo sysMessageInfo = new SysMessageInfo();
            sysMessageInfo.setId((long)messageId);
            sysMessageInfo.setGmtModified(new Date());
            sysMessageInfo.setHasRead((byte)1);
            result = sysMessageInfoMapper.updateByPrimaryKeySelective(sysMessageInfo);
        }
        return result;
    }


	
	@Override
	public Response userFeeExplain(String memberId,String type) throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			return Response.getError("未查询到该会员信息");
		}
		MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade==null){ 
			return Response.getError("用户未设置费率");
		}
		PayUserLevel payUserLevel=PayUserLevel.initialize(member.getPayGroupCode()); 
		PayLevelResult payLevelResult=IPayAPI.queryUserLevel(payUserLevel);
		if(!payLevelResult.getRespCode().equals("0000")) {
			return Response.getError("信息查询失败");
		}
		Byte usertype = 2;// 2表示用户3表示 商户
		String gradeRateId=memberGrade.getGradeRateId()+"";
//		String gradeRateId=memberGrade.getGradeRateId()+"";
		Map<String, String> map=null;
		for (int i = 0; i < payLevelResult.getLeves().size(); i++) {
			if(payLevelResult.getLeves().get(i).getType().equals(usertype)&&payLevelResult.getLeves().get(i).getLeveId().equals(gradeRateId)){
				map=payLevelResult.getLeves().get(i).getFeeInfo();
			}
		}
		if(map==null){//为空 显示默认费率说明
			for (int i = 0; i < payLevelResult.getLeves().size(); i++) {
				if(payLevelResult.getLeves().get(i).getLeveId().equals("EC")){
					map=payLevelResult.getLeves().get(i).getFeeInfo();
				}
			}
		} 
		String feeExplain=null;
		switch (type) {
		case "11":
			feeExplain=map.get(type);
			break;
		case "13":
			feeExplain=map.get(type);
			break;
		case "14":
			feeExplain=map.get(type);
			break;
		default:
			break;
		}
		return null;
	}
	
	
	@Override
	public Response feeExplain(String memberId,String type) throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			return Response.getError("未查询到该会员信息");
		}
		MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade==null){ 
			return Response.getError("用户未设置费率");
		}
		MemberFee memberFee=memberFeeMapper.selectByPrimaryKey(Integer.parseInt(String.valueOf(memberGrade.getMemberFeeId())));
		if(memberFee==null){
			return Response.getError("手续费费率未设置");
		}
		String example=null;
		StringBuffer feeExplainBuffer = new StringBuffer();
		StringBuffer exampleBuffer = new StringBuffer();
		
		String description=null;
		if(type.equals("15")){
			type="14";
			description="还款";
		}else if(type.equals("14")){
			description="提现";
		}
		
		
		//单一模式
		if(memberFee.getMode()==1){
			switch (type) {
			case "11":
				feeExplainBuffer.append("充值免费");
				exampleBuffer.append("例如：充值"+obtainRed("1000")+"元,则手续费为:"+obtainRed("0")+"(元)");
				break;
			case "13": 
				example="例如：转账"+obtainRed("1000")+"元,则手续费为:";
				Integer transferCount=null;
				String transferfee1=memberFee.getTransferType1()==1?obtainRed(Tools.moneyValue(memberFee.getTransferSingleAmt1())):"转账金额*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent1()));
				String transExample1=memberFee.getTransferType1()==1?obtainRed(Tools.moneyValue(memberFee.getTransferSingleAmt1())):obtainRed("1000*")+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent1()));
				transferCount=memberFee.getTransferType1()==1?memberFee.getTransferSingleAmt1():percentageCalculate(100000, memberFee.getTransferPercent1());
				feeExplainBuffer.append("转账手续费计算：").append(transferfee1);
				
				exampleBuffer.append(example).append(transExample1);
				if(memberFee.getTransferType1()==2){
					String yuan=obtainRed(Tools.moneyValue(transferCount));
					exampleBuffer.append("=").append(yuan);
				}
				break;
			case "14":
				example="例如："+description+obtainRed("1000")+"元,则手续费为:";
				Integer withdrawCount=null;
				String withdrawfee1=memberFee.getWithdrawType1()==1?obtainRed(Tools.moneyValue(memberFee.getWithdrawSingleAmt1())):""+description+"金额*"+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent1()));
				String withdrawExample1=memberFee.getWithdrawType1()==1?obtainRed(Tools.moneyValue(memberFee.getWithdrawSingleAmt1())):obtainRed("1000*")+Tools.percentageMoneyValue(memberFee.getWithdrawPercent1());
				withdrawCount=memberFee.getWithdrawType1()==1?memberFee.getWithdrawSingleAmt1():percentageCalculate(100000, memberFee.getWithdrawPercent1());
				feeExplainBuffer.append(""+description+"手续费计算：").append(withdrawfee1);
				exampleBuffer.append(example).append(withdrawExample1);
				if(memberFee.getWithdrawType1()==2){
					String yuan1=obtainRed(Tools.moneyValue(withdrawCount));
					exampleBuffer.append("=").append(yuan1);
				}
				break;
			default:
				break;
			}
			return Response.getSuccessExtend(feeExplainBuffer+"。",exampleBuffer+"。");
		}
		
		String yuan=null;
		//13个人转账 14个人提现 11充值    
		switch (type) {
		case "11":
			feeExplainBuffer.append("充值免费");
			exampleBuffer.append("例如：转账1000元,则手续费为:0(元)");
			break;
		case "13":
			example="例如：转账"+obtainRed("1000")+"元,则手续费为:";
			Integer transferFee1=null;
			Integer transferFee2=null;
			Integer transferFee3=null;
			Integer transferCount=null;
			String transferfee1=memberFee.getTransferType1()==1?obtainRed(Tools.moneyValue(memberFee.getTransferSingleAmt1())):"转账金额*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent1()));
			String transExample1=memberFee.getTransferType1()==1?obtainRed(Tools.moneyValueNo(memberFee.getTransferSingleAmt1())):obtainRed("1000*")+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent1()));
			transferFee1=memberFee.getTransferType1()==1?memberFee.getTransferSingleAmt1():percentageCalculate(100000, memberFee.getTransferPercent1());
			transferCount=transferFee1;
			feeExplainBuffer.append("转账手续费计算：").append(transferfee1);
			exampleBuffer.append(example).append(transExample1);
			if(memberFee.getTransferType2()!=null){
			 String transferfee2=memberFee.getTransferType2()==1?
					 obtainRed(Tools.moneyValue(memberFee.getTransferSingleAmt2())):"(转账金额-"+transferfee1+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent2()));
			 String transExample2=memberFee.getTransferType2()==1?
					 obtainRed(Tools.moneyValueNo(memberFee.getTransferSingleAmt2())):obtainRed("(1000-")+transferfee1+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent2()));	
			 transferFee2=memberFee.getTransferType2()==1?
					   memberFee.getTransferSingleAmt2():percentageCalculate(100000-transferFee1, memberFee.getTransferPercent2());	
					   transferCount=transferFee2+transferCount;		   
			feeExplainBuffer.append("+").append(transferfee2);
			exampleBuffer.append("+").append(transExample2);
						if(memberFee.getTransferType3()!=null){
							transferfee2=transferfee1+"-"+transferfee2;
							transExample2=transExample1+"-"+transExample2;
						String transferfee3=memberFee.getTransferType3()==1?
								obtainRed(Tools.moneyValue(memberFee.getTransferSingleAmt3())):"(转账金额-"+transferfee2+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent3()));
						String transExample3=memberFee.getTransferType3()==1?
								obtainRed(Tools.moneyValueNo(memberFee.getTransferSingleAmt3())):obtainRed("(1000-")+transExample2+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getTransferPercent3()));
						transferFee3=memberFee.getTransferType3()==1?
											   memberFee.getTransferSingleAmt3():percentageCalculate(100000-transferCount, memberFee.getTransferPercent3());	
							feeExplainBuffer.append("+").append(transferfee3);
							exampleBuffer.append("+").append(transExample3);
							transferCount=transferFee3+transferCount;
						}
			}
			if(memberFee.getTransferType2()!=null||memberFee.getTransferType1()!=1){
				yuan=obtainRed(Tools.moneyValue(transferCount));
				exampleBuffer.append("=").append(yuan);
			}else{
				exampleBuffer.append("元");
			}
			break;
		case "14":
			example="例如："+description+obtainRed("1000")+"元,则手续费为:";// withdraw_single_amt_1   withdraw_percent_1
			Integer withdrawFee1=null;  
			Integer withdrawFee2=null;
			Integer withdrawFee3=null;
			Integer withdrawCount=null;
			String withdrawfee1=memberFee.getWithdrawType1()==1?obtainRed(Tools.moneyValue(memberFee.getWithdrawSingleAmt1())):description+"金额*"+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent1()));
			String withdrawExample1=memberFee.getWithdrawType1()==1?obtainRed(Tools.moneyValueNo(memberFee.getWithdrawSingleAmt1())):obtainRed("1000*")+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent1()));
			withdrawFee1=memberFee.getWithdrawType1()==1?memberFee.getWithdrawSingleAmt1():percentageCalculate(100000, memberFee.getWithdrawPercent1());
			withdrawCount=withdrawFee1;
			feeExplainBuffer.append(""+description+"手续费计算：").append(withdrawfee1);
			exampleBuffer.append(example).append(withdrawExample1);
			if(memberFee.getWithdrawType2()!=null){ 
			 String withdrawfee2=memberFee.getWithdrawType2()==1?
					 obtainRed(Tools.moneyValue(memberFee.getWithdrawSingleAmt2())):"("+description+"金额-"+withdrawfee1+obtainRed(")*")+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent2()));
			 String withdrawExample2=memberFee.getWithdrawType2()==1?
					 obtainRed(Tools.moneyValueNo(memberFee.getWithdrawSingleAmt2())):obtainRed("(1000-")+withdrawfee1+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent2()));	
			 withdrawFee2=memberFee.getWithdrawType2()==1?
					   memberFee.getWithdrawSingleAmt2():percentageCalculate(100000-withdrawFee1, memberFee.getWithdrawPercent2());	
					   withdrawCount=withdrawFee2+withdrawCount;		   
			feeExplainBuffer.append("+").append(withdrawfee2);
			exampleBuffer.append("+").append(withdrawExample2);
						if(memberFee.getWithdrawType3()!=null){
							withdrawfee2=withdrawfee1+"-"+withdrawfee2;
							withdrawExample2=withdrawExample1+"-"+withdrawExample2;
						String withdrawfee3=memberFee.getWithdrawType3()==1?
								obtainRed(Tools.moneyValue(memberFee.getWithdrawSingleAmt3())):"("+description+"金额-"+withdrawfee2+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent3()));
						String withdrawExample3=memberFee.getWithdrawType3()==1?
								obtainRed(Tools.moneyValueNo(memberFee.getWithdrawSingleAmt3())):"(1000-"+withdrawExample2+")*"+obtainRed(Tools.percentageMoneyValue(memberFee.getWithdrawPercent3()));
						withdrawFee3=memberFee.getWithdrawType3()==1?
											   memberFee.getWithdrawSingleAmt3():percentageCalculate(100000-withdrawCount, memberFee.getWithdrawPercent3());	
							feeExplainBuffer.append("+").append(withdrawfee3);
							exampleBuffer.append("+").append(withdrawExample3);
							withdrawCount=withdrawFee3+withdrawCount;
						}
						
			}
			 if(memberFee.getWithdrawType2()!=null||memberFee.getWithdrawType1()!=1){
				 yuan=obtainRed(Tools.moneyValue(withdrawCount));
				 exampleBuffer.append("=").append(yuan);
				}else{
					exampleBuffer.append("元");
				}
			break;
		default:
			break;
		}
		return Response.getSuccessExtend(feeExplainBuffer+"。",exampleBuffer+"。");
	}
	
	public String obtainRed(String name){
//		return "<font color='red'>" + name + "</font>";
		return name;
	}
	
	/**
	 * 百分比计算
	 * @param worth 计算金额
	 * @param calculate 百分比
	 * @return
	 */
	public Integer percentageCalculate(Integer worth,Integer calculate){
		BigDecimal a1 = new BigDecimal(worth);
		BigDecimal a2 = new BigDecimal(calculate);//0.01% 代表1
		BigDecimal a3=a1.multiply(a2);
		BigDecimal bb3 = new BigDecimal(10000);
		BigDecimal result =a3.divide(bb3, 1);  
		return result.intValue();
	}
	
	
	
	@Override
	public Map<String, Object> selectFee(String memberId,Integer tranAmt,String type) throws ApplicationException {
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL,"会员信息不存在");
		}
		Map<String,Object> param=new HashMap<String,Object>();
        MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade!=null&&memberGrade.getMemberFeeId()!=null){
			System.out.println("----------------------------------本系统费率---------------------");
			MemberFee memberFee=memberFeeMapper.selectByPrimaryKey(Integer.parseInt(String.valueOf(memberGrade.getMemberFeeId())));
			if(memberFee==null){
				throw new ApplicationException(Rescode.FAIL,"手续费费率未设置");
			}
			if(memberFee.getMode()==1){
				 //单一费率
				 param=selectSingleFee(type,memberFee,tranAmt,member);
        	}else{
        		 //叠加费率
        		 param=selectSuperimposedFee(type,memberFee,Integer.valueOf(tranAmt),member);
        	}
			return param;
		}else{
				TransFeeCompute transFeeCompute=TransFeeCompute.initialize(member.getVirtualCard(), type, tranAmt+"", member.getPayGroupCode(), "1");
				PayFeeResult payResult=IPayAPI.memberByFee(transFeeCompute);
				if(!payResult.getRespCode().equals("0000")) {
					throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
				}
				param.put("fee", payResult.getUserFeeAt());
				param.put("outAmt", payResult.getOutAmt());
				return param;
		}
	}
	
	/**
	 * 单一费率
	 * @param type
	 * @param memberFee
	 * @param tranAmt 输入金额
	 * @param member
	 * @return
	 * @throws ApplicationException
	 */
	public HashMap<String, Object>  selectSingleFee(String type,MemberFee memberFee,Integer tranAmt,Member member) throws ApplicationException{
		HashMap<String,Object> param=new HashMap<String,Object>();
		switch (type) {
		case "4005": //转账   
			PayBalanceResult payResult=queryBalance(member);
			//可转账余额
			Integer balanceCount=Integer.parseInt(payResult.getCurBal())+Integer.parseInt(payResult.getCurBalB());
        	if(memberFee.getTransferType1()==1){  //1笔数2费率
        		param.put("fee", memberFee.getTransferSingleAmt1());
    			// 输入金额>手续费+可用余额
            	if(tranAmt>=memberFee.getTransferSingleAmt1()+balanceCount){
            		// 可使用金额=余额减去手续费
            		Integer outAmt=balanceCount-memberFee.getWithdrawPercent1();
            		param.put("outAmt", outAmt>0?outAmt:0);
            	}else{
            		param.put("outAmt", tranAmt);
            	}
        	}else if(memberFee.getTransferType1()==2){
        		//实际计算金额
        		Integer calculateFee=tranAmt-balanceCount>0?balanceCount:tranAmt;
        		BigDecimal a1 = new BigDecimal(calculateFee);
    			BigDecimal a2 = new BigDecimal(memberFee.getWithdrawPercent1());//折扣  withdraw_percent_1
    			BigDecimal a3=a1.multiply(a2);
    			BigDecimal bb3 = new BigDecimal(10000);
    			//分以下舍弃 9.9分 取值9分
    			BigDecimal result =a3.divide(bb3, 1);  
    			Integer fee=result.intValue();
    			param.put("outAmt", queryOutAmt(fee, balanceCount, tranAmt));
    			param.put("fee", fee);
        	}
			break;
        case "4007": 
        	PayBalanceResult payResult1=queryBalance(member);
        	Integer curBal=Integer.parseInt(payResult1.getCurBal());
        	if(memberFee.getWithdrawType1()==1){   //1笔数2费率   withdraw_single_amt_1
        		Integer withdrawSingleAmt1=memberFee.getWithdrawSingleAmt1();
        		param.put("fee", withdrawSingleAmt1);
        		//提现输入金额>=手续费+卡余额     返回可转最大金额
            	if(tranAmt>=withdrawSingleAmt1+curBal){ 
            		Integer outAmt=curBal-withdrawSingleAmt1;
            		param.put("outAmt", outAmt>0?outAmt:0);
            	}else{
            		param.put("outAmt", tranAmt);
            	}
        	}else if(memberFee.getWithdrawType1()==2){
        		//实际计算金额
        		Integer calculateFee=tranAmt-curBal>0?curBal:tranAmt;
        		BigDecimal a1 = new BigDecimal(calculateFee);
    			BigDecimal a2 = new BigDecimal(memberFee.getWithdrawPercent1());//折扣  withdraw_percent_1  withdraw_percent_1
    			BigDecimal a3=a1.multiply(a2);
    			BigDecimal bb3 = new BigDecimal(10000);
    			BigDecimal result =a3.divide(bb3, 1);  
    			Integer fee=result.intValue(); 
    			param.put("outAmt", queryOutAmt(fee, curBal, tranAmt));
    			param.put("fee", fee);
        	}
			break;
        case "4006": 
        	if(memberFee.getRechargeType1()==1){   //1笔数2费率
        		param.put("fee", memberFee.getRechargeSingleAmt1());
            	param.put("outAmt", tranAmt);
        	}else if(memberFee.getRechargeType1()==2){
        		//实际计算金额
        		BigDecimal a1 = new BigDecimal(tranAmt);
    			BigDecimal a2 = new BigDecimal(memberFee.getWithdrawPercent1());//折扣  withdraw_percent_1
    			BigDecimal a3=a1.multiply(a2);
    			BigDecimal bb3 = new BigDecimal(10000);
    			//分以下舍弃 9.9分 取值9分
    			BigDecimal result =a3.divide(bb3, 1);  
    			Integer fee=result.intValue();
    			param.put("fee", fee);
        	}
			break;
		}
		return param;
	}
	
	   /**
	    * 
	    * @param type
	    * @param memberFee
	    * @param tranAmt  输入金额
	    * @param member
	    * @return
	    * @throws ApplicationException
	    */
		public HashMap<String, Object>  selectSuperimposedFee(String type,MemberFee memberFee,Integer tranAmt,Member member) throws ApplicationException{
			HashMap<String,Object> param=new HashMap<String,Object>();
			Integer feeCount=null;
				switch (type) {
				case "4005": //转账
					PayBalanceResult payResult0=queryBalance(member);
		        	//可用转账余额
		        	Integer curBal0=Integer.parseInt(payResult0.getCurBal())+Integer.parseInt(payResult0.getCurBalB());
		        	if(memberFee.getTransferType1()==1){
		        		     //单一费率1   
			        		FeeOutDTO feeOutDTO1=oneFee(memberFee.getTransferSingleAmt1(), tranAmt,curBal0);
			        		if(memberFee.getTransferType2()!=null&&memberFee.getTransferType2()==1){
			        			//单一费率 2
			        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
				        			if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==1){
				        				//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        			param.put("fee", feeCount);
						            	param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        			}else if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==2){
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getTransferPercent3(), memberFee.getTransferPercentMax3(), 
				        						memberFee.getTransferPercentMin3(), feeOutDTO2.getActualMoney(),curBal0);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        				param.put("fee", feeCount);
				        				param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        			}else{
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
					        			param.put("fee", feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        			}
			        		}else if(memberFee.getTransferType2()!=null&&memberFee.getTransferType2()==2){
			        			 //叠加费率2 
			        			FeeOutDTO feeOutDTO2=complex(memberFee.getTransferPercent2(), memberFee.getTransferPercentMax2(), 
		        						memberFee.getTransferPercentMin2(), tranAmt,curBal0);
				        			  if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==1){
				        				  	//单一费率 3
					        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
					        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
						        			param.put("fee", feeCount);
						        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        				
				        			}else if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==2){//叠加费率3
					        				//叠加费率3
					        				FeeOutDTO feeOutDTO3=complex(memberFee.getTransferPercent3(), memberFee.getTransferPercentMax3(), 
					        						memberFee.getTransferPercentMin3(), feeOutDTO2.getActualMoney(),curBal0);
					        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        				param.put("fee", feeCount);
					        				param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        			}else{
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
					        			param.put("fee", feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
				        			   }
			        		}else{
			        			feeCount=feeOutDTO1.getFee();
			        			param.put("fee", feeCount);
			        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        		}
		        	}else if(memberFee.getTransferType1()==2){
		        		//叠加费率1
        				FeeOutDTO feeOutDTO1=complex(memberFee.getTransferPercent1(), memberFee.getTransferPercentMax1(), 
        						memberFee.getTransferPercentMin1(), tranAmt,curBal0);
        				if(memberFee.getTransferType2()!=null&&memberFee.getTransferType2()==1){
		        			//单一费率 2
		        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
			        			if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==1){
			        				//单一费率 3
			        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        			param.put("fee", feeCount);
				        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        			}else if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==2){
			        				//叠加费率3
			        				FeeOutDTO feeOutDTO3=complex(memberFee.getTransferPercent3(), memberFee.getTransferPercentMax3(), 
			        						memberFee.getTransferPercentMin3(), feeOutDTO2.getActualMoney(),curBal0);
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
			        				param.put("fee",feeCount );
			        				param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        			}else{
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
				        			param.put("fee",feeCount );
				        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        			}
		        		}else if(memberFee.getTransferType2()!=null&&memberFee.getTransferType2()==2){
		        			 //叠加费率2 
		        			FeeOutDTO feeOutDTO2=complex(memberFee.getTransferPercent2(), memberFee.getTransferPercentMax2(), 
	        						memberFee.getTransferPercentMin2(), tranAmt,curBal0);
			        			  if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==1){
			        				  	//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getTransferSingleAmt2(), feeOutDTO1.getActualMoney(),curBal0);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        			param.put("fee",feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        				
			        			}else if(memberFee.getTransferType3()!=null&&memberFee.getTransferType3()==2){//叠加费率3
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getTransferPercent3(), memberFee.getTransferPercentMax3(), 
				        						memberFee.getTransferPercentMin3(), feeOutDTO2.getActualMoney(),curBal0);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        				param.put("fee", feeCount);
				        				param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        			}else{
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
				        			param.put("fee", feeCount);
				        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
			        			   }
		        		}else{
		        			feeCount=feeOutDTO1.getFee();
		        			param.put("fee",feeCount );
		        			param.put("outAmt", queryOutAmt(feeCount, curBal0, tranAmt));
		        		   }
		        	}
					break;
		        case "4007": //提现   
		        	PayBalanceResult payResult1=queryBalance(member);
		        	//可用提现余额
		        	Integer curBal=Integer.parseInt(payResult1.getCurBal());
		        	if(memberFee.getWithdrawType1()==1){
		        		     //单一费率1   
			        		FeeOutDTO feeOutDTO1=oneFee(memberFee.getWithdrawSingleAmt1(), tranAmt,curBal);
			        		if(memberFee.getWithdrawType2()!=null&&memberFee.getWithdrawType2()==1){
			        			//单一费率 2
			        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
				        			if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==1){
				        				//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        			param.put("fee",feeCount );
					        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        			}else if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==2){
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getWithdrawPercent3(), memberFee.getWithdrawPercentMax3(), 
				        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),curBal);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        				param.put("fee", feeCount);
				        				param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        			}else{
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
					        			param.put("fee",feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        			}
			        		}else if(memberFee.getWithdrawType2()!=null&&memberFee.getWithdrawType2()==2){
			        			 //叠加费率2 
			        			FeeOutDTO feeOutDTO2=complex(memberFee.getWithdrawPercent2(), memberFee.getWithdrawPercentMax2(), 
		        						memberFee.getWithdrawPercentMin2(), tranAmt,curBal);
				        			  if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==1){
				        				  	//单一费率 3
					        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
					        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
						        			param.put("fee", feeCount);
						        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        				
				        			}else if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==2){//叠加费率3
					        				//叠加费率3
					        				FeeOutDTO feeOutDTO3=complex(memberFee.getWithdrawPercent3(), memberFee.getWithdrawPercentMax3(), 
					        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),curBal);
					        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        				param.put("fee", feeCount);
					        				param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        			}else{
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
					        			param.put("fee", feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
				        			   }
			        		}else{
			        			feeCount=feeOutDTO1.getFee();
			        			param.put("fee", feeCount);
			        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        		}
		        	}else if(memberFee.getWithdrawType1()==2){
		        		//叠加费率1
        				FeeOutDTO feeOutDTO1=complex(memberFee.getWithdrawPercent1(), memberFee.getWithdrawPercentMax1(), 
        						memberFee.getWithdrawPercentMin1(), tranAmt,curBal);
        				if(memberFee.getWithdrawType2()!=null&&memberFee.getWithdrawType2()==1){
		        			//单一费率 2
		        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
			        			if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==1){
			        				//单一费率 3
			        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        			param.put("fee",feeCount);
				        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        			}else if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==2){
			        				//叠加费率3
			        				FeeOutDTO feeOutDTO3=complex(memberFee.getWithdrawPercent3(), memberFee.getWithdrawPercentMax3(), 
			        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),curBal);
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
			        				param.put("fee", feeCount);
			        				param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        			}else{
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
				        			param.put("fee",feeCount);
				        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        			   }
		        		}else if(memberFee.getWithdrawType2()!=null&&memberFee.getWithdrawType2()==2){
		        			 //叠加费率2 
		        			FeeOutDTO feeOutDTO2=complex(memberFee.getWithdrawPercent2(), memberFee.getWithdrawPercentMax2(), 
	        						memberFee.getWithdrawPercentMin2(), tranAmt,curBal);
			        			  if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==1){
			        				  	//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getWithdrawSingleAmt2(), feeOutDTO1.getActualMoney(),curBal);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
					        			param.put("fee", feeCount);
					        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        				
			        			}else if(memberFee.getWithdrawType3()!=null&&memberFee.getWithdrawType3()==2){//叠加费率3
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getWithdrawPercent3(), memberFee.getWithdrawPercentMax3(), 
				        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),curBal);
				        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee();
				        				param.put("fee", feeCount);
				        				param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        			}else{
			        				feeCount=feeOutDTO1.getFee()+feeOutDTO2.getFee();
				        			param.put("fee", feeCount);
				        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
			        			   }
		        		}else{
		        			feeCount=feeOutDTO1.getFee();
		        			param.put("fee", feeCount);
		        			param.put("outAmt", queryOutAmt(feeCount, curBal, tranAmt));
		        		   }
		        	}
					break;
		        case "4006": //充值   recharge_single_amt_1    recharge_type_2
		        	if(memberFee.getRechargeType1()==1){
		        		     //单一费率1   
			        		FeeOutDTO feeOutDTO1=oneFee(memberFee.getRechargeSingleAmt1(), tranAmt,null);
			        		if(memberFee.getRechargeType2()!=null&&memberFee.getRechargeType2()==1){
			        			//单一费率 2
			        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
				        			if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==1){
				        				//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
					        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
						            	param.put("outAmt", tranAmt);
				        			}else if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==2){
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getRechargeSingleAmt3(), memberFee.getWithdrawPercentMax3(), 
				        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),null);
				        				param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
						            	param.put("outAmt", tranAmt);
				        			}else{
					        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee());
						            	param.put("outAmt", tranAmt);
				        			}
			        		}else if(memberFee.getRechargeType2()!=null&&memberFee.getRechargeType2()==2){
			        			 //叠加费率2 
			        			FeeOutDTO feeOutDTO2=complex(memberFee.getRechargeSingleAmt2(), memberFee.getWithdrawPercentMax2(), 
		        						memberFee.getWithdrawPercentMin2(), tranAmt,null);
				        			  if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==1){
				        				  	//单一费率 3
					        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
						        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
							            	param.put("outAmt", tranAmt);
				        				
				        			}else if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==2){//叠加费率3
					        				//叠加费率3
					        				FeeOutDTO feeOutDTO3=complex(memberFee.getRechargeSingleAmt3(), memberFee.getWithdrawPercentMax3(), 
					        						memberFee.getWithdrawPercentMin3(), feeOutDTO2.getActualMoney(),null);
					        				param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
							            	param.put("outAmt", tranAmt);
				        			}else{
					        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee());
						            	param.put("outAmt", tranAmt);
				        			   }
			        		}else{
			        			param.put("fee", feeOutDTO1.getFee());
				            	param.put("outAmt", tranAmt);	
			        		}
		        	}else if(memberFee.getRechargeType1()==2){
		        		//叠加费率1
        				FeeOutDTO feeOutDTO1=complex(memberFee.getRechargeSingleAmt1(), memberFee.getRechargePercentMax1(), 
        						memberFee.getRechargePercentMin1(), tranAmt,null);
        				if(memberFee.getRechargeType2()!=null&&memberFee.getRechargeType2()==1){
		        			//单一费率 2
		        			FeeOutDTO feeOutDTO2=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
			        			if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==1){
			        				//单一费率 3
			        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
				        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
					            	param.put("outAmt", tranAmt);
			        			}else if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==2){
			        				//叠加费率3
			        				FeeOutDTO feeOutDTO3=complex(memberFee.getRechargeSingleAmt3(), memberFee.getRechargePercentMax3(), 
			        						memberFee.getRechargePercentMin3(), feeOutDTO2.getActualMoney(),null);
			        				param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
					            	param.put("outAmt", tranAmt);
			        			}else{
				        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee());
					            	param.put("outAmt", tranAmt);
			        			   }
		        		}else if(memberFee.getRechargeType2()!=null&&memberFee.getRechargeType2()==2){
		        			 //叠加费率2 
		        			FeeOutDTO feeOutDTO2=complex(memberFee.getRechargeSingleAmt2(), memberFee.getRechargePercentMax2(), 
	        						memberFee.getRechargePercentMin2(), tranAmt,null);
			        			  if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==1){
			        				  	//单一费率 3
				        				FeeOutDTO feeOutDTO3=oneFee(memberFee.getRechargeSingleAmt2(), feeOutDTO1.getActualMoney(),null);
					        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
						            	param.put("outAmt", tranAmt);
			        				
			        			}else if(memberFee.getRechargeType3()!=null&&memberFee.getRechargeType3()==2){//叠加费率3
				        				//叠加费率3
				        				FeeOutDTO feeOutDTO3=complex(memberFee.getRechargeSingleAmt3(), memberFee.getRechargePercentMax3(), 
				        						memberFee.getRechargePercentMin3(), feeOutDTO2.getActualMoney(),null);
				        				param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee()+feeOutDTO3.getFee());
						            	param.put("outAmt", tranAmt);
			        			}else{
				        			param.put("fee", feeOutDTO1.getFee()+feeOutDTO2.getFee());
					            	param.put("outAmt", tranAmt);
			        			   }
		        		}else{
		        			param.put("fee", feeOutDTO1.getFee());
			            	param.put("outAmt", tranAmt);	
		        		   }
		        	}
					break;
				}
				
				return param;
			}
		
		/**
		 * 复合单笔手续费
		 * @param withdrawSingleAmt     单笔多少元
		 * @param actualMoney           计算金额
		 * @param balanceCount 余额
		 * @return
		 */
		public FeeOutDTO oneFee(Integer withdrawSingleAmt,Integer actualMoney,Integer balanceCount){
			FeeOutDTO feeOutDTO=new FeeOutDTO();
			if(balanceCount!=null){
				// 输入金额>手续费+可用余额
	        	if(actualMoney>=withdrawSingleAmt+balanceCount){
	        		// 可计算金额>=手续费+可用余额(不包括充值)
	        		feeOutDTO.setFee(withdrawSingleAmt); 
	    			feeOutDTO.setActualMoney(balanceCount-withdrawSingleAmt); 
	        	}else{
	        		feeOutDTO.setFee(withdrawSingleAmt); 
	    			feeOutDTO.setActualMoney(actualMoney-withdrawSingleAmt); 
	        	}
			}else{
				    feeOutDTO.setFee(withdrawSingleAmt); 
    			    feeOutDTO.setActualMoney(actualMoney-withdrawSingleAmt);
			}
			return feeOutDTO;
		}
		
		
		/**
		 * 复合百分比手续费
		 * @param withdrawPercent   提现单笔百分比
		 * @param percentMax        按照百分比，最大额度
		 * @param percentmin        按照百分比，最小额度
		 * @param tranAmt           计算金额
		 * @param balanceCount      余额
		 * @return
		 */
		public FeeOutDTO complex(Integer withdrawPercent,Integer percentMax,Integer percentmin,Integer tranAmt,Integer balanceCount){
			FeeOutDTO feeOutDTO=new FeeOutDTO();
			//实际计算金额
			Integer tran=null;
			if(balanceCount!=null){
				//计算金额>余额
					if(tranAmt>balanceCount){
						tran=balanceCount;
					}else{
						tran=tranAmt;
					}
			}else{
				tran=tranAmt;
			}
			
			BigDecimal a1 = new BigDecimal(tran);
			BigDecimal a2 = new BigDecimal(withdrawPercent);//100% 代表10000
			BigDecimal a3=a1.multiply(a2);
			BigDecimal bb3 = new BigDecimal(10000);
		//	BigDecimal result =a3.divide(bb3, 2);  
			//分以下舍弃 9.9分 取值9分
			BigDecimal result =a3.divide(bb3, 1);  
			Integer fee=result.intValue();
			Integer feeTree=null;
			
			Integer maxAmount=percentMax==null?0:percentMax;
			Integer minAmount=percentmin==null?0:percentmin;
			
			if(fee>maxAmount){
				feeTree=maxAmount;
			}else if(fee<minAmount){
				feeTree=minAmount;
			}else{
				feeTree=result.intValue();
			}
			feeOutDTO.setFee(feeTree);
			feeOutDTO.setActualMoney(tran-feeTree); 
			return feeOutDTO;
	}
		
		
		/**
		 * 计算输出金额  输出金额超过可用余额 输出可交易金额最大值
		 * @param feeCount  总手续费
		 * @param curBal    余额
		 * @param tranAmt   前端输入金额
		 * @return
		 * @throws ApplicationException
		 */
		public Integer queryOutAmt(Integer feeCount,Integer curBal,Integer tranAmt) throws ApplicationException{
			// 前端输入金额+手续费>余额
			if(tranAmt+feeCount>curBal){
				return curBal-feeCount;
			}else{
				return tranAmt;
			}
		}
		
		
		
		/**
		 * 查询余额
		 * @param member
		 * @return
		 * @throws ApplicationException
		 */
		public PayBalanceResult queryBalance(Member member) throws ApplicationException{
			
			Wallet wallet=walletService.selectwallet(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId());
			PayBalanceResult  payResult=new PayBalanceResult();
			payResult.setCurBal(wallet.getCanBalance()+""); 
			payResult.setCurBalB(wallet.getNocanBalance()+""); 
			return payResult;
		}

	@Override
	public HashMap<String, Object> updateWxlyWithdraw(String memberId, Integer tranAmt, String cardId, String payPwd,Integer fee)
			throws ApplicationException {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		Member member = memberMapper.queryGroup(Long.parseLong(memberId));
		if(member==null){
			throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
		}
		MemberCard memberCard =  memberCardMapper.selectInfo(Long.parseLong(cardId),Long.parseLong(memberId));
		if(memberCard==null){
			throw new ApplicationException(Rescode.FAIL, "银行卡信息不存在");
		}
		MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade==null||memberGrade.getWalletCanConsume()==false){
			throw new ApplicationException(Rescode.FAIL, "提现申请失败,您的帐户未获得提现权限");
		}
		//兼容老用户
				if(member.getTradePassword().equals("888888")){
					member.setTradePassword(AES.AESEncode(Const.AceKey, payPwd));  
					memberMapper.updateByPrimaryKeySelective(member);
				}else{
					if (!AES.AESEncode(Const.AceKey, payPwd).equals(member.getTradePassword())) {
						throw new ApplicationException(Rescode.FAIL, "支付密码错误!");
					}
				}
		String orgOrderNum=Const.WX_WITHDEAW+UtilFun.createOrderNum();
		Date date=new Date();
		 TradeOffline tradeOffline=new TradeOffline();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(member.getGroupId());
		    tradeOffline.setOrderId(UtilFun.createOrderNum());
		    tradeOffline.setPayerId(member.getId());//付款者id号
		    tradeOffline.setPayerName(member.getName());//付款者姓名
		    tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setPayType((byte)BizEnum.PaymentType.Wallet.getType());//支付方式 生成订单支付方式未知
		    tradeOffline.setReceiverId(member.getId()+"");//接收者id        提现付款者接收者暂设置为同一
		    tradeOffline.setReceiverName(member.getName());//接收者 此处以核销录入数据
		    tradeOffline.setReceiverType((byte)CommonEnum.UserType.User.getType());
		    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Withdraw.getType());//交易类型
		    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(tranAmt); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(tranAmt);//实付金额
//		    tradeOffline.setRelatedActivityId(null);//关联活动
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Proccessing.getType());//交易状态
		    tradeOffline.setIsWallet(true);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMemo("微信钱包用户申请提现");
		    tradeOffline.setDetail("微信钱包用户申请提现");
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount(memberCard.getCardNum());//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setPayOrderid(orgOrderNum);
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构
		    tradeOffline.setFee(fee);
		    tradeOfflineMapper.insertSelective(tradeOffline);
		    hashMap.put("member", member);
		    hashMap.put("memberCard", memberCard);
		    hashMap.put("memberGrade", memberGrade);
		    hashMap.put("orgOrderNum", orgOrderNum);
			return hashMap;
	}
	@Override
	public Response sendWxlyWithdraw(HashMap<String, Object> hashMap, Integer tranAmt, String payPwd,Integer fee)
			throws ApplicationException {
		Map<String, Object> map = new HashMap<String, Object>();
		Member member = (Member) hashMap.get("member");
		MemberCard memberCard =  (MemberCard) hashMap.get("memberCard");
		String orgOrderNum=hashMap.get("orgOrderNum").toString();
		  
		    PayWithdrawalResult result =walletService.updateBankWithdrawal(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(), tranAmt,
					orgOrderNum, payPwd, memberCard.getCardNum(), memberCard.getBankIntegral(), memberCard.getIdName(), memberCard.getIssuerBankName(), fee);
			if(result==null || result.getVerificationStatus().byteValue()==0x00){
				logger.info(PayWithdrawalResult.getNotNullMsgTxt(result, "提现申请提交失败,通信异常"));
				throw new ApplicationException(Rescode.FAIL, "提现申请提交失败,通信异常");
			}else{
				if(Rescode.SUCCESS.equals(result.getRespCode())){
					map.put("actualAt", result.getActualAt());
					map.put("status", result.getStatus());
					map.put("feeAt", result.getFeeAt());
					map.put("orderId", result.getOrderId());
					map.put("msgTxt", result.getMsgTxt());
				   return Response.getSuccess(map);
				}else{
					throw new ApplicationException(result.getRespCode(), result.getMsgTxt());
				}
			}
		    
	}

	@Override
	public Response shopSaleList(Long memberId, Integer pageNo, Integer pageSize, Integer status) {
		Integer pageStart = (pageNo - 1) * pageSize;
		List<Map<String, Object>> data = orderShopMapper.listMemberShopOrder(memberId, pageStart, pageSize, status);
		return Response.getSuccess(data);
	}

	@Override
	public Response shopSaleOrderDetail(Long memberId, Long shopId, String orderId,String user_latitude, String user_longitude) throws Exception {
		Map<String, Object> data = shopMapper.getShopDetailById(shopId);

		String tolongitude = (String) data.get("tolongitude");
		String tolatitude = (String) data.get("tolatitude");
		long calDistance = -1;

		//tx转百度
		Map<String, Object> stringObjectMap2 = QqMapApiHelper.Convert_GCJ02_To_BD09(Double.parseDouble(tolatitude),Double.parseDouble(tolongitude));
		//坐标转换
		double longitude2=Double.parseDouble(stringObjectMap2.get("toLongitude").toString());
		double latitude2=Double.parseDouble(stringObjectMap2.get("toLatitude").toString());
		data.put("tolatitude",latitude2);
		data.put("tolongitude",longitude2);

		if(!Tools.isEmpty(user_latitude) && !Tools.isEmpty(user_longitude)) {
			Map<String, Object> stringObjectMap = new HashMap<>();
			if(StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude)) {
				//坐标转换
				stringObjectMap = QqMapApiHelper.Convert_BD09_To_GCJ02(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude));
			}

			if(StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude)
					&& StringUtil.notEmpty(tolongitude)&& StringUtil.notEmpty(tolatitude)){

				//坐标转换tring
				String longitude=stringObjectMap.get("toLongitude").toString();
				String latitude=stringObjectMap.get("toLatitude").toString();

				calDistance = QqMapApiHelper.getDistance(QqMapApiHelper.MODE_DRIVING,latitude,longitude,tolatitude,tolongitude);
				if(calDistance>0){
					data.put("shopLocation",calDistance);
				}else{
					double s = LocationUtils.getDistance(Double.parseDouble(latitude), Double.parseDouble(longitude), Double.parseDouble(tolatitude), Double.parseDouble(tolongitude));
					data.put("shopLocation",(long)s);
				}
			}else{
				data.put("shopLocation",calDistance);
			}
		}

		Map<String, Object> oldTransInfo = orderShopMapper.getTradeDetailByOrderNo(orderId);
		data.put("oldTransInfo", oldTransInfo);
		Integer status = (Integer) oldTransInfo.get("status");
		if(status == BizEnum.ShopOrderStatus.Refunding.getType()) {
			//todo refund
		} else if(status == BizEnum.ShopOrderStatus.OrderFinished.getType()) {
			Map<String, Object> completeInfo = mallGoodCommentMapper.getCommentDetailByOrderNo(orderId);

			if((String) completeInfo.get("pics")!=null){
			String pics = (String) completeInfo.get("pics");
			String[] pics1 = pics.split(",");
			for(int i = 0; i < pics1.length; i++) {
				completeInfo.put("comment_imagepath" + (i + 1), pics1[i]);
			}
			completeInfo.remove("pics");
			}
			//取出内容base64解码
//			String content = (String) completeInfo.get("comment_content");
//			completeInfo.put("comment_content", new String(Base64Utils.decode(content)));
			data.put("completeInfo", completeInfo);
		}
		return Response.getSuccess(data);
	}

	@Override
	public Response saveShopSaleOrderEvaluate(Long memberId, Long shopId, String orderId, String evaluateContent, Integer evaluateSorce, Boolean isAnonymous, String picUrls) {
		Date date = new Date();

		OrderShop orderShop = orderShopMapper.getOrderShopByOrderNo(orderId);
		ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectByShopId(shopId);
		orderShop.setStatus(BizEnum.ShopOrderStatus.OrderFinished.getType());
		orderShop.setGmtModified(date);
		MallGoodComment mallGoodComment = new MallGoodComment();
		mallGoodComment.setCreaterId(memberId);
		mallGoodComment.setCommentLevel(evaluateSorce);
		mallGoodComment.setCommentType(BizEnum.CommentType.Shop.getType());
		mallGoodComment.setGmtCreate(date);
		mallGoodComment.setGmtModified(date);
		mallGoodComment.setOrderId(orderShop.getId());
		mallGoodComment.setShopId(shopId);
		mallGoodComment.setGroupId(shopGroupRelation.getGroupId());
		//这个地方base64编码
//		String base64Str = Base64Utils.encode(evaluateContent);
		mallGoodComment.setContent(evaluateContent);
		mallGoodComment.setIsCryptonym(isAnonymous);
		mallGoodComment.setPicUrls(picUrls);
		mallGoodComment.setGroupId(shopGroupRelation.getGroupId());

		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(shopGroupRelation.getGroupId());
		if(groupConfig == null || groupConfig.getCheckStatus()) {
			mallGoodComment.setAuditStatus(1);
		} else {
			mallGoodComment.setAuditStatus(0);
		}
		int i = orderShopMapper.updateByPrimaryKey(orderShop);
		if(i == 1) {
			int j = mallGoodCommentMapper.insert(mallGoodComment);
			if(j == 1) {
				return Response.buildSuccess("评价添加成功");
			}
		}
		return Response.getError("评价失败");
	}

	public Map<String, Object> couponhavegottendetail(String memberId,String couponuserId) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
		}
		if (Tools.isEmpty(couponuserId)) {
			throw new ApplicationException(Rescode.FAIL, "couponId不能为空！");
		}
		CouponUser couponUser = couponUserMapper.selectByPrimaryKey(Long.parseLong(couponuserId));
		if(couponUser == null){
			throw new ApplicationException(Rescode.FAIL, "couponuserId为：" + couponuserId + "的记录为空！");
		}
		Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
		if(coupon == null){
			throw new ApplicationException(Rescode.FAIL, "couponId为：" + couponUser.getCouponId() + "的记录为空！");
		}
		//获取券码二维码base64字符流
		String couponQrcodestr = CodeUtil.getBase64QRcodeStr(QRCodeParams.initialize(couponUser.getCouponCode(),
				400, 400, 0xFF000000, 0xFFFFFFFF, 2, null));

		if(coupon != null){
			map.put("coupon_id",coupon.getId());
			map.put("coupon_icon","");
			map.put("coupon_code",couponUser.getCouponCode());
			map.put("coupon_qrcodestr",couponQrcodestr);
			map.put("coupon_type", ActivityEnum.CouponType.fromType(coupon.getCouponType()).getName());
			map.put("exchange_place",coupon.getExchangePlace());
			map.put("purpose_type", coupon.getPurposeType());
			//exchange_place 为1 商品类型good_type 写死了3  exchange_place为2 的时候 good_type 1:表示服务商品 2 商城商品
			if(coupon.getExchangePlace()==1){
				map.put("good_type",3);
			}else{
				map.put("good_type", coupon.getGoodType());
			}
			map.put("coupon_name",coupon.getName());
			map.put("coupon_money",CouponHelp.getFaceValueStr(coupon.getCouponType(),coupon.getValue()));
			map.put("coupon_qualification",AmountUtils.changeF2Y(coupon.getLimitAmount()==null?0:coupon.getLimitAmount().longValue()));
			String startTime = DateUtil.fomatDate(couponUser.getValidStartTime(),DateUtil.sdfDay);
			String endTime = DateUtil.fomatDate(couponUser.getValidTime(),DateUtil.sdfDay);
			map.put("coupon_valid_time", (startTime==null?"":startTime) + "至" + (endTime==null?"":endTime));
			map.put("coupon_peruser",coupon.getAmountPeruser());
			map.put("verify_readd_count",coupon.getVerifyReaddCount());


		}
		return map;

	}

	@Override
	public Response findOrderNum(String orderId)throws ApplicationException {
		TradeOffline record=tradeOfflineMapper.selectByOrderIdStatus(orderId,(byte)BizEnum.TransactionStatus.Success.getType());      
		if(record==null){// receiver_id
			return Response.getError("未查询到交易记录");
		} 
		Member member=memberMapper.selectByPrimaryKey(Long.valueOf(record.getReceiverId())); 
		if(member==null){
			return Response.getError("未查询到该会员");
		} 
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("transfer_time", DateUtil.fomatDate(record.getGmtCreate(),DateUtil.sdfTime));
		resultMap.put("transfer_to_name", member.getName());
		resultMap.put("transfer_to_phone", member.getPhone());
		resultMap.put("transfer_money", record.getOrderAmount());
		resultMap.put("transfer_fee", record.getFee());
		
		return Response.getSuccess(resultMap);
	}

	@Override
	public Response rechargeBenefit(Long memberId) {
		Date date = new Date();
		Member member = memberMapper.selectByPrimaryKey(memberId);
		ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(member.getGroupId(), date);
		Map<String, Object> getRechargeInfo = new HashMap<>();
		if(activityUnroutine == null) {
			getRechargeInfo.put("rechargeType", 3);
		} else {
			List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutine.getActivityId());
			List<Map<String, Object>> combineInfo = new ArrayList<>();
			for(int i = 0; i < activityUnroutineRuleList.size(); i++) {
				Map<String, Object> combine = new HashMap<>();
				ActivityUnroutineRule aur = activityUnroutineRuleList.get(i);
				combine.put("bid", aur.getId());
				combine.put("real_pay_money", aur.getMiniAmount());
				combine.put("real_get_money", aur.getFaceValue());
				combineInfo.add(combine);
			}
			if(activityUnroutineRuleList.get(0).getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
				getRechargeInfo.put("rechargeType", 1);
				getRechargeInfo.put("combineInfo", combineInfo);
			} else {
				getRechargeInfo.put("rechargeType", 2);
				getRechargeInfo.put("percentageInfo", combineInfo);
			}
		}
		return Response.getSuccess(getRechargeInfo);
	}

	@Override
	public Response memberWalletCompetence(Long memberId) {
		Member member = memberMapper.selectByPrimaryKey(memberId);
		if(member==null){
			return Response.getError("未查询到该会员");
		}
		MemberGrade memberGrade=memberGradeMapper.selectByPrimaryKey(member.getGradeId());
		if(memberGrade==null){
			return Response.getError("会员等级不存在");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("can_develope_member", memberGrade.getCanDevelopeMember()!=null&&memberGrade.getCanDevelopeMember()==true?"1":"0");
		map.put("wallet_can_consume", memberGrade.getWalletCanConsume()!=null&&memberGrade.getWalletCanConsume()==true?"1":"0");
		map.put("wallet_can_recharge", memberGrade.getWalletCanRecharge()!=null&&memberGrade.getWalletCanRecharge()==true?"1":"0");
		map.put("wallet_can_transfer", memberGrade.getWalletCanTransfer()!=null&&memberGrade.getWalletCanTransfer()==true?"1":"0");
		map.put("wallet_can_receive", memberGrade.getWalletCanReceive()!=null&&memberGrade.getWalletCanReceive()==true?"1":"0");
		map.put("can_withdraw", memberGrade.getCanWithdraw()!=null&&memberGrade.getCanWithdraw()==true?"1":"0");
		return Response.getSuccess(map);
	}

	@Override
	public Response getServiceCouponsList(Long memberId,Long goodOrShopId, Integer tradeMoney) throws Exception {
		List<Map<String, Object>> list=couponUserService.listUserCouponsInfo(memberId, goodOrShopId, tradeMoney, 
				ActivityEnum.ActivityPlatformType.OnLine, CommonEnum.GoodType.Service);
		return Response.getSuccess(list);
	}

	@Override
	public String subscribeUrl(String homeUrl,SubscribeMemberDTO subscribeMember,String nickname,String openId) {
		//注册首页
		String url = homeUrl + "/api/oAuth2/urlSubscribe?openId="+openId+"&type="+subscribeMember.getType();
		if(subscribeMember.getGroupId()==21L){
			StringBuffer sb=new StringBuffer();
			sb.append("\t\t\t\t");
			sb.append("恭喜您关注【田好】微信公众号。");
			sb.append("\n");
			sb.append("\n");
			sb.append("\t\t\t\t如果您愿意注册成为会员，您将获得专属二维码，分享您的二维码或者您的专属海报到朋友圈、微信群或者直接推送给您的朋友，您就可获得20元代金券。");
			sb.append("\n");
			sb.append("\n");
			sb.append("\t\t\t\t更刺激的是：如果您推广的朋友在现场和电商平台消费后您都能享受相应奖励。");
			sb.append("\n");
			sb.append("\n");
			sb.append("<a href=\"" +url+ "\">"+"点击此处"+"</a>");
			sb.append("\t注册成为会员");
			return sb.toString();
		}else if(subscribeMember.getGroupId()==16L){
			//  感谢您关注“iCLEAN 爱可净”微信公众号，我们已赠送您免费体验1次标准洗衣的机会，（完善会员信息）后，还可再获得1次免费体验。点击「进入首页」-充值享优惠，更多优惠等你享有。
			StringBuffer sb=new StringBuffer();
			sb.append("\t\t\t\t");
			sb.append("感谢您关注“iCLEAN 爱可净”微信公众号，我们已赠送您免费体验1次标准洗衣的机会，");
			sb.append("<a href=\"" +url+ "\">"+"(完善会员信息)"+"</a>");
			sb.append("后，还可再获得1次免费体验。点击「进入首页」-充值享优惠，更多优惠等你享有。");
			sb.append("\t注册成为会员");
			return sb.toString();
		}else{
			String  href = "<a href=\"" +url+ "\">" +"完善会员信息"+ "</a>";
			String content="欢迎成为"+subscribeMember.getMerchantName()+"的会员!请先完善您的会员信息："+href+" 完成后即可开始邀请好友加入，共享会员超级福利!";
		    return content;
		}
		
		
	}
	
	@Override
	public String subscribeSendEnvelope(String homeUrl,SubscribeMemberDTO subscribeMember,String nickname,String hrefName) {
		String url=String.format("%s/"+subscribeMember.getGroupId()+"/redpacket_list.html",homeUrl);
		String href = "<a href=\"" +url+ "\">" +hrefName+ "</a>";
		String content="尊敬的"+nickname+"，您获得一个会员红包,点击"+href;
		return content;
	}

	@Override
	public String subscribeMember(String homeUrl, SubscribeMemberDTO subscribeMember, String nickname,
			String hrefName) {
		String url=String.format("%s/"+subscribeMember.getGroupId()+"/share_to.html?uid="+subscribeMember.getMemberId(),homeUrl);
//		String href = "<a href=\"" +url+ "\">" +hrefName+ "</a>";
//		String content="尊敬的"+nickname+"，您已经关注了点击"+href+",快去邀请会员吧";
		
		String href = "<a href=\"" +url+ "\">" +hrefName+ "</a>";
		String  content="欢迎回来，您已是"+subscribeMember.getMerchantName()+"的会员!"+href+" 点击邀请好友，共享会员超级福利";
		return content;
	}

	@Override
	public Map<String, Object> findMemberDisCount(String memberId) {
		Map<String, Object> map = new HashMap<String, Object>();
		MemberGradeOutDTO memberGradeOutDTO = memberMapper.findMemberDisCount(Long.parseLong(memberId));
		if(memberGradeOutDTO != null){
			map.put("member_disCount",memberGradeOutDTO.getDiscountRate());
		}
		return map;
	}
}

